MongoDB 中 “select distinct(name) from collectionName where age = “25”” 的等效物是什么?
您可以使用 distinct() 获得和 select 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 }
以下查询等效于 `select distinct(name) from collectionName where age = “25” −`
> db.distinctNameAndAgeDemo.distinct("ClientFirstName", {"Age": 25});
这将生成以下输出 -
[ "Larry", "David", "Sam" ]
上面,我们显示了年龄为 25 的客户的姓名。
广告