在MongoDB中按值查找像结构这样的字典?
您可以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"
}
}
}