MongoDB查询嵌入式文档中的字段?
首先让我们创建一个包含文档的集合-
> db.embeddedDocumentDemo.insertOne( ... { ... "CustomerDetails":[ ... {"CustomerName":"Chris", "CustomerPurchasePrice":3000}, ... {"CustomerName":"Robert", "CustomerPurchasePrice":4500}, ... {"CustomerName":"David", "CustomerPurchasePrice":1000}, ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd32347edc6604c74817ccd") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.embeddedDocumentDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd32347edc6604c74817ccd"), "CustomerDetails" : [ { "CustomerName" : "Chris", "CustomerPurchasePrice" : 3000 }, { "CustomerName" : "Robert", "CustomerPurchasePrice" : 4500 }, { "CustomerName" : "David", "CustomerPurchasePrice" : 1000 } ] }
以下是嵌入式文档的查询-
> db.embeddedDocumentDemo.find({"CustomerDetails.CustomerPurchasePrice":4500});
这将产生以下输出-
{ "_id" : ObjectId("5cd32347edc6604c74817ccd"), "CustomerDetails" : [ { "CustomerName" : "Chris", "CustomerPurchasePrice" : 3000 }, { "CustomerName" : "Robert", "CustomerPurchasePrice" : 4500 }, { "CustomerName" : "David", "CustomerPurchasePrice" : 1000 } ] }