要通过两个键删除重复的条目,请在MongoDB中使用Aggregate()。让我们创建一个包含文档的集合-
> db.demo108.insertOne({"Value1":23,"Value2":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e2ee3e49fd5fd66da214477") } > db.demo108.insertOne({"Value1":23,"Value2":25}); { "acknowledged" : true, "insertedId" : ObjectId("5e2ee3f29fd5fd66da214478") } > db.demo108.insertOne({"Value1":23,"Value2":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e2ee3f59fd5fd66da214479") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo108.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2ee3e49fd5fd66da214477"), "Value1" : 23, "Value2" : 24 } { "_id" : ObjectId("5e2ee3f29fd5fd66da214478"), "Value1" : 23, "Value2" : 25 } { "_id" : ObjectId("5e2ee3f59fd5fd66da214479"), "Value1" : 23, "Value2" : 24 }
以下是通过MongoDB中的两个键删除重复条目的查询-
> db.demo108.aggregate([{ "$sort": { "_id": 1 } }, ... { ... "$group": { ... "_id": { "Value1": "$Value1", "Value2": "$Value2" }, ... "doc": { "$first": "$$ROOT" } ... } ... }, ... { "$replaceRoot": { "newRoot": "$doc" } }, ... { "$out": "demo108" }]);
在find()方法的帮助下显示集合中的所有文档-
> db.demo108.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2ee3f29fd5fd66da214478"), "Value1" : 23, "Value2" : 25 } { "_id" : ObjectId("5e2ee3e49fd5fd66da214477"), "Value1" : 23, "Value2" : 24 }