在 MongoDB 中的物件陣列中查詢具有兩個特定識別符號的所有文件?


對此可以使用 $and 運算子。我們先用文件建立一個集合 -

> db.twoSpecificIdsDemo.insertOne(
...   {
...      PlayerId:1,
...      "PlayerDetails": [{
...         id: 100,
...         "PlayerName":"Chris"
...      },{
...         id: 101,
...         "PlayerName":"Sam"
...      },{
...         id: 102,
...         "PlayerName":"Robert"
...      },{
...         id: 103,
...         "PlayerName":"Carol"
...      }]
...   }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3e130edc6604c74817ce4")
}
> db.twoSpecificIdsDemo.insertOne(
...   {
...      PlayerId:1,
...      "PlayerDetails": [{
...         id: 104,
...         "PlayerName":"Mike"
...      },{
...         id: 105,
...         "PlayerName":"Bob"
...      },{
...         id: 102,
...         "PlayerName":"Ramit"
...      },{
...         id: 106,
...         "PlayerName":"David"
...      }]
...   }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3e167edc6604c74817ce5")
}

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

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

這將產生以下輸出 -

{
   "_id" : ObjectId("5cd3e130edc6604c74817ce4"),
   "PlayerId" : 1,
   "PlayerDetails" : [
      {
         "id" : 100,
         "PlayerName" : "Chris"
      },
      {
         "id" : 101,
         "PlayerName" : "Sam"
      },
      {
         "id" : 102,
         "PlayerName" : "Robert"
      },
      {
         "id" : 103,
         "PlayerName" : "Carol"
      }
   ]
}
{
   "_id" : ObjectId("5cd3e167edc6604c74817ce5"),
   "PlayerId" : 1,
   "PlayerDetails" : [
      {
         "id" : 104,
         "PlayerName" : "Mike"
      },
      {
         "id" : 105,
         "PlayerName" : "Bob"
      },
      {
         "id" : 102,
         "PlayerName" : "Ramit"
      },
      {
         "id" : 106,
         "PlayerName" : "David"
      }
   ]
}

以下是查詢在 MongoDB 中的物件陣列中查詢具有兩個特定識別符號的所有文件 -

> db.twoSpecificIdsDemo.find( { $and : [ { "PlayerDetails.id" : 102 }, { "PlayerDetails.id" : 103 } ] } ).pretty();

這將產生以下輸出 -

{
   "_id" : ObjectId("5cd3e130edc6604c74817ce4"),
   "PlayerId" : 1,
   "PlayerDetails" : [
      {
         "id" : 100,
         "PlayerName" : "Chris"
      },
      {
         "id" : 101,
         "PlayerName" : "Sam"
      },
      {
         "id" : 102,
         "PlayerName" : "Robert"
      },
      {
         "id" : 103,
         "PlayerName" : "Carol"
      }
   ]
}

更新於: 30-Jul-2019

78 人瀏覽

啟動你的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.