如何从Mongodb中数组中的文档投影特定字段?
要从数组中的文档投影特定字段,可以使用位置($)运算符。
首先让我们创建一个包含文档的集合
> db.projectSpecificFieldDemo.insertOne( ... { ... "UniqueId": 101, ... "StudentDetails" : [{"StudentName" : "Chris", "StudentCountryName ": "US"}, ... {"StudentName" : "Robert", "StudentCountryName" : "UK"}, ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ca27aeb6304881c5ce84ba2") } > db.projectSpecificFieldDemo.insertOne( { "UniqueId": 102, "StudentDetails" : [{"StudentName" : "Robert", "StudentCountryName ": "UK"}, {"StudentName" : "David", "StudentCountryName" : "AUS"}, ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5ca27b106304881c5ce84ba3") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.projectSpecificFieldDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5ca27aeb6304881c5ce84ba2"), "UniqueId" : 101, "StudentDetails" : [ { "StudentName" : "Chris", "StudentCountryName " : "US" }, { "StudentName" : "Robert", "StudentCountryName" : "UK" } ] } { "_id" : ObjectId("5ca27b106304881c5ce84ba3"), "UniqueId" : 102, "StudentDetails" : [ { "StudentName" : "Robert", "StudentCountryName " : "UK" }, { "StudentName" : "David", "StudentCountryName" : "AUS" } ] }
以下是查询以从数组内的文档投影特定字段的查询
> var myDocument = { UniqueId : 101, 'StudentDetails.StudentName' : 'Chris' }; > var myProjection= {'StudentDetails.$': 1 }; > db.projectSpecificFieldDemo.find(myDocument , myProjection).pretty();
这将产生以下输出
{ "_id" : ObjectId("5ca27aeb6304881c5ce84ba2"), "StudentDetails" : [ { "StudentName" : "Chris", "StudentCountryName " : "US" } ] }