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

更新於: 2019-07-30

282 次瀏覽

開啟你的 職業生涯

完成課程認證

開始
廣告
© . All rights reserved.