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

Tìm trong từ điển như cấu trúc theo giá trị với MongoDB?

Bạn có thể sử dụng find () 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.findInDictionaryDemo.insertOne(
...    {
...       "_id":101,
...       "AllCustomerDetails":
...       {
...          "SomeCustomerDetail1":
...          {
...             "CustomerName1":"John Doe",
...             "CustomerName2":"John Smith"
...          },
...          "SomeCustomerDetail2":
...          {
...             "CustomerName1":"Carol Taylor",
...             "CustomerName2":"David Miller"
...          }
...       }
...    }
... );
{ "acknowledged" : true, "insertedId" : 101 }

> db.findInDictionaryDemo.insertOne(
...    {
...       "_id":102,
...       "AllCustomerDetails":
...       {
...          "SomeCustomerDetail1":
...          {
...             "CustomerName1":"Sam Wiliams",
...             "CustomerName2":"Bob Johnson"
...          },
...          "SomeCustomerDetail2":
...          {
...             "CustomerName1":"Chris Brown",
...             "CustomerName2":"Mike Wilson"
...          }
...       }
...    }
... );
{ "acknowledged" : true, "insertedId" : 102 }

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.findInDictionaryDemo.find().pretty();

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

{
   "_id" : 101,
   "AllCustomerDetails" : {
      "SomeCustomerDetail1" : {
         "CustomerName1" : "John Doe",
         "CustomerName2" : "John Smith"
      },
      "SomeCustomerDetail2" : {
         "CustomerName1" : "Carol Taylor",
         "CustomerName2" : "David Miller"
      }
   }
}
{
   "_id" : 102,
   "AllCustomerDetails" : {
      "SomeCustomerDetail1" : {
         "CustomerName1" : "Sam Wiliams",
         "CustomerName2" : "Bob Johnson"
      },
      "SomeCustomerDetail2" : {
         "CustomerName1" : "Chris Brown",
         "CustomerName2" : "Mike Wilson"
      }
   }
}

Sau đây là truy vấn để tìm trong từ điển theo giá trị trong MongoDB -

>db.findInDictionaryDemo.find({"AllCustomerDetails.SomeCustomerDetail2.CustomerName2":"Mike Wilson"}).pretty();

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

{
   "_id" : 102,
   "AllCustomerDetails" : {
      "SomeCustomerDetail1" : {
         "CustomerName1" : "Sam Wiliams",
         "CustomerName2" : "Bob Johnson"
      },
      "SomeCustomerDetail2" : {
         "CustomerName1" : "Chris Brown",
         "CustomerName2" : "Mike Wilson"
      }
   }
}