问题描述
我有这样的文件:
{
"_id" : ObjectId("557eaf444ba222d545c3dffc"),
"foreing" : ObjectId("538726124ba2222c0c0248ae"),
"value" : "test",
}
我想找到所有对 foreing
& 具有重复值的文档值
.
I want to find all documents which have duplicated values for pair foreing
& value
.
推荐答案
您可以通过运行以下聚合管道操作轻松识别重复项:
You can easily identify the duplicates by running the following aggregation pipeline operation:
db.collection.aggregate([
{
"$group": {
"_id": { "foreing": "$foreing", "value": "$value" },
"uniqueIds": { "$addToSet": "$_id" },
"count": { "$sum": 1 }
}
},
{ "$match": { "count": { "$gt": 1 } } }
])
$group第一步中的code>
操作符用于按foreign
和value
键值对文档进行分组,然后创建一个_id 每个分组文档的值作为 uniqueIds
字段使用 $addToSet
运算符.这为您提供了每个组的唯一表达式值数组.使用 $sum
运算符.
The $group
operator in the first step is used to group the documents by the foreign
and value
key values and then create an array of _id
values for each of the grouped documents as the uniqueIds
field using the $addToSet
operator. This gives you an array of unique expression values for each group. Get the total number of grouped documents to use in the later pipeline stages with the $sum
operator.
在第二个管道阶段,使用 $match
操作符过滤掉所有计数为 1 的文档.过滤掉的文档代表唯一的索引键.
In the second pipeline stage, use the $match
operator to filter out all documents with a count of 1. The filtered-out documents represent unique index keys.
剩余的文档将是集合中那些对 foreing
& 具有重复键值的文档.值
.
The remaining documents will be those in the collection that have duplicate key values for pair foreing
& value
.
这篇关于Mongo 查找两个或多个字段的条目的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!