在 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"
}
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP