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 } ] }
广告