MongoDB 投影结果作为选定项目的数组?
让我们创建一个包含文档的集合 −
> db.demo151.insertOne({"ListOfNames":["Chris","David","Mike"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3513b6fdf09dd6d08539da") } > db.demo151.insertOne({"ListOfNames":["Mike","Bob"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3513c4fdf09dd6d08539db") } > db.demo151.insertOne({"ListOfNames":["John","David","Chris"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3513dcfdf09dd6d08539dc") }
使用 find() 方法显示集合中的所有文档 −
> db.demo151.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e3513b6fdf09dd6d08539da"), "ListOfNames" : [ "Chris", "David", "Mike" ] } { "_id" : ObjectId("5e3513c4fdf09dd6d08539db"), "ListOfNames" : [ "Mike", "Bob" ] } { "_id" : ObjectId("5e3513dcfdf09dd6d08539dc"), "ListOfNames" : [ "John", "David", "Chris" ] }
以下是将投影结果作为选定项目的数组的查询 −
> db.demo151.distinct('_id', {'ListOfNames' : "Mike"});
这将产生以下输出 −
[ ObjectId("5e3513b6fdf09dd6d08539da"), ObjectId("5e3513c4fdf09dd6d08539db") ]
广告