对于嵌套查询,让我们首先创建包含文档的集合-
> db.demo492.insertOne({ ... "ProductDetails" : ... { ... "StockDetails" : [ ... { "ProductName" : "Product-1" }, ... {"ProductName" : "Product-2"}, ... { "ProductName" : "Product-3"} ... ... ] ... ... } ... }); { "acknowledged" : true, "insertedId" : ObjectId("5e849db8b0f3fa88e22790c2") } > > > > db.demo492.insertOne({ ... "ProductDetails" : ... { ... "StockDetails" : [ ... { "ProductName" : "Product-4" }, ... {"ProductName" : "Product-5"}, ... { "ProductName" : "Product-6"} ... ... ] ... ... } ... }); { "acknowledged" : true, "insertedId" : ObjectId("5e849dceb0f3fa88e22790c3") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo492.find();
这将产生以下输出-
{ "_id" : ObjectId("5e849db8b0f3fa88e22790c2"), "ProductDetails" : { "StockDetails" : [ { "ProductName" : "Product-1" }, { "ProductName" : "Product-2" }, { "ProductName" : "Product3" } ] } } { "_id" : ObjectId("5e849dceb0f3fa88e22790c3"), "ProductDetails" : { "StockDetails" : [ { "ProductName" : "Product-4" }, { "ProductName" : "Product-5" }, { "ProductName" : "Product6" } ] } }
以下显示在MongoDB中使用点表示法来获取特定文档的嵌套查询-
> db.demo492.find({ "ProductDetails.StockDetails.ProductName":"Product-1"});
这将产生以下输出-
{ "_id" : ObjectId("5e849db8b0f3fa88e22790c2"), "ProductDetails" : { "StockDetails" : [ { "ProductName" : "Product-1" }, { "ProductName" : "Product-2" }, { "ProductName" : "Product3" } ] } }