Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Tìm trong cấu trúc kiểu dictionary theo giá trị với MongoDB?

Dùng find() với ký pháp chấm (dot notation) truy cập nested object. Tạo collection:

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

Hiển thị tất cả:

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

Tìm document có AllCustomerDetails.SomeCustomerDetail2.CustomerName2 = "Mike Wilson":

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

Kết quả: