您可以为此使用$slice运算符。首先让我们创建一个包含文档的集合-
> db.firstElementOfArray.insertOne( ... { ... _id: 100, ... "Details": [ ... { ... "CustomerName": "John", ... "CustomerCountryName":"US" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 100 } > db.firstElementOfArray.insertOne( ... { ... _id: 101, ... "Details": [ ... { ... "CustomerName": "Carol", ... "CustomerCountryName":"UK" ... }, ... { ... "CustomerName": "David", ... "CustomerCountryName":"AUS" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.firstElementOfArray.find().pretty();
这将产生以下输出-
{ "_id" : 100, "Details" : [ { "CustomerName" : "John", "CustomerCountryName" : "US" } ] } { "_id" : 101, "Details" : [ { "CustomerName" : "Carol", "CustomerCountryName" : "UK" }, { "CustomerName" : "David", "CustomerCountryName" : "AUS" } ] }
以下是查找数组第一个元素的属性的查询-
> db.firstElementOfArray.find({},{'Details':{$slice:1},'Details.CustomerName':1}).pretty();
这将产生以下输出-
{ "_id" : 100, "Details" : [ { "CustomerName" : "John" } ] } { "_id" : 101, "Details" : [ { "CustomerName" : "Carol" } ] }