利用 MongoDB 中的数组元素获取特定文档
若要获取特定文档,请在 MongoDB find() 中使用点符号。让我们创建一个包含文档的集合 -
> db.demo672.insertOne({Brand:[{CategoryName:"Mobile","Name":"Oppo"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5ea3ea9b04263e90dac943e5") } > db.demo672.insertOne({Brand:[{CategoryName:"Mobile","Name":"Samsung"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5ea3eaa404263e90dac943e6") } > db.demo672.insertOne({Brand:[{CategoryName:"Mobile","Name":"OnePlus"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5ea3eacc04263e90dac943e7") }
借助 find() 方法显示集合中的所有文档 -
> db.demo672.find();
这将产生以下输出 -
{ "_id" : ObjectId("5ea3ea9b04263e90dac943e5"), "Brand" : [ { "CategoryName" : "Mobile", "Name" : "Oppo" } ] } { "_id" : ObjectId("5ea3eaa404263e90dac943e6"), "Brand" : [ { "CategoryName" : "Mobile", "Name" : "Samsung" } ] } { "_id" : ObjectId("5ea3eacc04263e90dac943e7"), "Brand" : [ { "CategoryName" : "Mobile", "Name" : "OnePlus" } ] }
以下是获取特定文档的查询 -
> db.demo672.find({"Brand.Name":"OnePlus"});
这将产生以下输出 -
{ "_id" : ObjectId("5ea3eacc04263e90dac943e7"), "Brand" : [ { "CategoryName" : "Mobile", "Name" : "OnePlus" } ] }
广告