要将重复的文档分组,请使用MongoDB aggregate()
。让我们创建一个包含文档的集合-
> db.demo501.insertOne({"Name":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8752f0987b6e0e9d18f566") } > db.demo501.insertOne({"Name":"Bob"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8752f4987b6e0e9d18f567") } > db.demo501.insertOne({"Name":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8752f8987b6e0e9d18f568") } > db.demo501.insertOne({"Name":"John"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8752fb987b6e0e9d18f569") } > db.demo501.insertOne({"Name":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8752fd987b6e0e9d18f56a") } > db.demo501.insertOne({"Name":"John"});{ "acknowledged" : true, "insertedId" : ObjectId("5e875301987b6e0e9d18f56b") } > db.demo501.insertOne({"Name":"David"});{ "acknowledged" : true, "insertedId" : ObjectId("5e875307987b6e0e9d18f56c") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo501.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8752f0987b6e0e9d18f566"), "Name" : "Chris" } { "_id" : ObjectId("5e8752f4987b6e0e9d18f567"), "Name" : "Bob" } { "_id" : ObjectId("5e8752f8987b6e0e9d18f568"), "Name" : "Chris" } { "_id" : ObjectId("5e8752fb987b6e0e9d18f569"), "Name" : "John" } { "_id" : ObjectId("5e8752fd987b6e0e9d18f56a"), "Name" : "Chris" } { "_id" : ObjectId("5e875301987b6e0e9d18f56b"), "Name" : "John" } { "_id" : ObjectId("5e875307987b6e0e9d18f56c"), "Name" : "David" }
以下是对MongoDB中重复文档进行分组的查询-
> db.demo501.aggregate( [ { $group : { _id : "$Name" } } ] )
这将产生以下输出-
{ "_id" : "David" } { "_id" : "John" } { "_id" : "Bob" } { "_id" : "Chris" }