MongoDB等价于`collectionName中选择“ distinct(name)”,其中age =“ 25”?
您可以使用distinct()来获取选择distinct的等效项。首先让我们创建一个包含文档的集合-
> db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"John","Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cd12759e3526dbddbbfb60b") } > db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"Larry","Age":25}); { "acknowledged" : true, "insertedId" : ObjectId("5cd12768e3526dbddbbfb60c") } > db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"David","Age":25}); { "acknowledged" : true, "insertedId" : ObjectId("5cd12773e3526dbddbbfb60d") } > db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"Carol","Age":26}); { "acknowledged" : true, "insertedId" : ObjectId("5cd1277ee3526dbddbbfb60e") } > db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"Sam","Age":25}); { "acknowledged" : true, "insertedId" : ObjectId("5cd12793e3526dbddbbfb60f") } > db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"Larry","Age":25}); { "acknowledged" : true, "insertedId" : ObjectId("5cd127a3e3526dbddbbfb610") } > db.distinctNameAndAgeDemo.insertOne({"ClientFirstName":"Carol","Age":26}); { "acknowledged" : true, "insertedId" : ObjectId("5cd127aae3526dbddbbfb611") }
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.distinctNameAndAgeDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd12759e3526dbddbbfb60b"), "ClientFirstName" : "John", "Age" : 23 } { "_id" : ObjectId("5cd12768e3526dbddbbfb60c"), "ClientFirstName" : "Larry", "Age" : 25 } { "_id" : ObjectId("5cd12773e3526dbddbbfb60d"), "ClientFirstName" : "David", "Age" : 25 } { "_id" : ObjectId("5cd1277ee3526dbddbbfb60e"), "ClientFirstName" : "Carol", "Age" : 26 } { "_id" : ObjectId("5cd12793e3526dbddbbfb60f"), "ClientFirstName" : "Sam", "Age" : 25 } { "_id" : ObjectId("5cd127a3e3526dbddbbfb610"), "ClientFirstName" : "Larry", "Age" : 25 } { "_id" : ObjectId("5cd127aae3526dbddbbfb611"), "ClientFirstName" : "Carol", "Age" : 26 }
以下查询等效于`collectionName中的selectdifferent(name),其中age=“25”-
> db.distinctNameAndAgeDemo.distinct("ClientFirstName", {"Age": 25});
这将产生以下输出-
[ "Larry", "David", "Sam" ]
在上方,我们显示了年龄25岁的客户名称。