要仅显示唯一记录,请在MongoDB中使用distinct()。让我们创建一个包含文档的集合-
> db.demo613.insertOne({"Name":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e988bd4f6b89257f5584d88") } > db.demo613.insertOne({"Name":"Bob"});{ "acknowledged" : true, "insertedId" : ObjectId("5e988bdbf6b89257f5584d89") } > db.demo613.insertOne({"Name":"Bob"});{ "acknowledged" : true, "insertedId" : ObjectId("5e988bddf6b89257f5584d8a") } > db.demo613.insertOne({"Name":"David"});{ "acknowledged" : true, "insertedId" : ObjectId("5e988be0f6b89257f5584d8b") } > db.demo613.insertOne({"Name":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e988be2f6b89257f5584d8c") } > db.demo613.insertOne({"Name":"Sam"});{ "acknowledged" : true, "insertedId" : ObjectId("5e988be8f6b89257f5584d8d") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo613.find();
这将产生以下输出-
{ "_id" : ObjectId("5e988bd4f6b89257f5584d88"), "Name" : "Chris" } { "_id" : ObjectId("5e988bdbf6b89257f5584d89"), "Name" : "Bob" } { "_id" : ObjectId("5e988bddf6b89257f5584d8a"), "Name" : "Bob" } { "_id" : ObjectId("5e988be0f6b89257f5584d8b"), "Name" : "David" } { "_id" : ObjectId("5e988be2f6b89257f5584d8c"), "Name" : "Chris" } { "_id" : ObjectId("5e988be8f6b89257f5584d8d"), "Name" : "Sam" }
以下是获取唯一记录的查询-
> db.demo613.distinct("Name");
这将产生以下输出-
[ "Chris", "Bob", "David", "Sam" ]