獲取包含陣列中特定屬性的 MongoDB 文件


為此,可以使用 $and 和點(.)符號。我們先建立一個帶有文件的集合 -

>db.demo2.insertOne({"StudentInformation":[{"StudentName":"John","StudentAge":21},{"StudentName":"Mike","StudentAge":22}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e08b56e25ddae1f53b62219")
}
>db.demo2.insertOne({"StudentInformation":[{"StudentName":"Carol","StudentAge":19},{"StudentName":"Bob","StudentAge":18}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e08b58625ddae1f53b6221a")
}

以下是使用 find() 方法顯示集合中所有文件的查詢 -

> db.demo2.find().pretty();

這將產生以下輸出 -

{
   "_id" : ObjectId("5e08b56e25ddae1f53b62219"),
   "StudentInformation" : [
      {
         "StudentName" : "John",
         "StudentAge" : 21
      },
      {
         "StudentName" : "Mike",
         "StudentAge" : 22
      }
   ]
}
{
   "_id" : ObjectId("5e08b58625ddae1f53b6221a"),
   "StudentInformation" : [
      {
         "StudentName" : "Carol",
         "StudentAge" : 19    
     },    
     {
         "StudentName" : "Bob",
         "StudentAge" : 18
      }
   ]
}

以下是獲取包含陣列中特定屬性的文件的查詢 -

>db.demo2.find({$and:[{"StudentInformation.StudentName":"Carol"},{"StudentInformation.StudentName":"Bob"}]});

這將產生以下輸出 -

{ "_id" : ObjectId("5e08b58625ddae1f53b6221a"), "StudentInformation" : [ { "StudentName" : "Carol", "StudentAge" : 19 }, { "StudentName" : "Bob", "StudentAge" : 18 } ] }

更新日期:2020 年 3 月 31 日

468 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告