如何在 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" } ] }
广告