คุณสามารถใช้ 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" } } }