投影结果是MongoDB中所选项目的数组?
distinct()
为此使用,因为它会在单个集合或视图中查找指定字段的不同值,然后将结果返回到数组中。
首先让我们创建一个包含文档的集合-
> db.projectionListDemo.insertOne({"_id":"1","Subject":["MongoDB","MySQL","Java"]}); { "acknowledged" : true, "insertedId" : "1" } > db.projectionListDemo.insertOne({"_id":"2","Subject":["MongoDB","C","C++"]}); { "acknowledged" : true, "insertedId" : "2" } > db.projectionListDemo.insertOne({"_id":"3","Subject":["Java","Python"]}); { "acknowledged" : true, "insertedId" : "3" }
在find()
方法的帮助下显示集合中的所有文档-
> db.projectionListDemo.find().pretty();
输出结果
{ "_id" : "1", "Subject" : [ "MongoDB", "MySQL", "Java" ] } { "_id" : "2", "Subject" : [ "MongoDB", "C", "C++" ] } { "_id" : "3", "Subject" : [ "Java", "Python" ] }
现在,让我们以选定项目的数组形式获得结果-
> db.projectionListDemo.distinct('_id', {'Subject' : 'MongoDB'});
输出结果
[ "1", "2" ]