Computer >> Máy Tính >  >> Lập trình >> MongoDB

Tìm tất cả các tài liệu có hai id cụ thể trong một mảng đối tượng trong MongoDB?

Bạn có thể sử dụng $ và toán tử cho việc này. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -

> 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")
}

Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -

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

Điều này sẽ tạo ra kết quả sau -

{
   "_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"
      }
   ]
}

Đây là truy vấn để tìm tất cả các tài liệu có hai id cụ thể trong một mảng đối tượng trong MongoDB -

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

Điều này sẽ tạo ra kết quả sau -

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