要从列中获取不同的值,请distinct()
在MongoDB中使用。首先让我们创建一个包含文档的集合-
> db.demo128.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30583d68e7f832db1a7f5d") } > db.demo128.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30584068e7f832db1a7f5e") } > db.demo128.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30584368e7f832db1a7f5f") } > db.demo128.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30584668e7f832db1a7f60") } > db.demo128.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e30584c68e7f832db1a7f61") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo128.find();
这将产生以下输出-
{ "_id" : ObjectId("5e30583d68e7f832db1a7f5d"), "Name" : "Chris" } { "_id" : ObjectId("5e30584068e7f832db1a7f5e"), "Name" : "David" } { "_id" : ObjectId("5e30584368e7f832db1a7f5f"), "Name" : "David" } { "_id" : ObjectId("5e30584668e7f832db1a7f60"), "Name" : "Bob" } { "_id" : ObjectId("5e30584c68e7f832db1a7f61"), "Name" : "Chris" }
以下是从MongoDB中的列获取不同值的查询-
> db.demo128.distinct("Name");
这将产生以下输出-
[ "Chris", "David", "Bob" ]