在 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" } } }
广告