使用 MongoDB 按值在类似字典的结构中查找?

mongodbdatabasebig data analytics更新于 2026/1/16 8:22:17

您可以使用 find() 来实现。首先,我们创建一个包含文档的集合。 −

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

以下是使用 find() 方法显示集合中的所有文档的查询 −

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

这将产生以下输出 −

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

以下是在 MongoDB 中按值在字典中查找的查询 −

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

这将产生以下输出 −

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

相关文章