若要访问数组值,请使用点(。)表示法。让我们创建一个包含文档的集合-
> db.demo326.insertOne({id:101,"ProductDetails":[{"ProductId":"Prod-101","ProductName":"Product-1"}, ... {"ProductId":"Prod-102","ProductName":"Product-2"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e516751f8647eb59e562074") } > db.demo326.insertOne({id:103,"ProductDetails":[{"ProductId":"Prod-104","ProductName":"Product-5"}, ... {"ProductId":"Prod-105","ProductName":"Product-6"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e516771f8647eb59e562075") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo326.find();
这将产生以下输出-
{ "_id" : ObjectId("5e516751f8647eb59e562074"), "id" : 101, "ProductDetails" : [ { "ProductId" : "Prod-101", "ProductName" : "Product-1" }, { "ProductId" : "Prod-102", "ProductName" : "Product-2" } ] } { "_id" : ObjectId("5e516771f8647eb59e562075"), "id" : 103, "ProductDetails" : [ { "ProductId" : "Prod-104", "ProductName" : "Product-5" }, { "ProductId" : "Prod-105", "ProductName" : "Product-6" } ] }
以下是查询以访问MongoDB集合中的数组并获取特定文档的查询-
> db.demo326.find({"ProductDetails.ProductId":"Prod-104"});
这将产生以下输出-
{ "_id" : ObjectId("5e516771f8647eb59e562075"), "id" : 103, "ProductDetails" : [ { "ProductId" : "Prod-104", "ProductName" : "Product-5" }, { "ProductId" : "Prod-105", "ProductName" : "Product-6" } ] }