在 MongoDB 集合中查找相同的元素

Find the same element in MongoDB Collection

我有这样的数据结构:

myStructure = {
    1 : ['ab','bc','cd','gh'] , 
    2 : ['bc','cd','de'] , 
    3 : ['cd','de','ef12','xz','ygd']
}

我想找到 'myStructure' 内所有数组中都存在的元素,即:'cd'

我要向 MongoDB 输入大量数据,我想像上面的例子一样找到 patterns/duplicates...

有什么方法可以用 MongoDB 做到这一点吗?没有 MongoDB 有更好的方法吗?

更新 1:

我注意到我的数据结构不是一个更可取的...我不想仅限于几个键,如“1,2,3”,因此我将结构更改为:

    myStructure = [
        {key: 1, value: ['ab','bc','cd']} ,
        {key: 2, value: ['bc','cd','de']} ,
        {key: 3, value: ['cd','de','ef']},
        ...
    ]

感谢您到目前为止的回答,但如果您能根据新结构回答问题,我将不胜感激...谢谢...

您需要的是使用 $setIntersection 运算符进行聚合。

db.test.aggregate(
    [
        { $project: { "commonElement": { $setIntersection: [ "", "", "" ]}}}
    ]
)

如果您的意思是所有数组始终存在,那么您可以使用 $setIntersection and $redact:

db.collection.aggregate([
    { "$redact": {
        "$cond": {
           "if": { 
               "$gt": [
                   { "$size": { "$setIntersection": ["","", ""] } },
                   0
               ]
           },
           "then": "$$KEEP",
           "else": "$$PRUNE"
       }
    }},
    { "$project": {
        "intersection": { "$setIntersection": ["","",""] }
    }}
])

首先过滤任何不相交的东西,然后显示交集。

所以对于同一文档中的所有数组:

{ 
    "_id" : ObjectId("559a22f8369e4e157fe17338"), 
    "1" : [ "ab", "bc", "cd" ], 
    "2" : [ "bc", "cd", "de" ], 
    "3" : [ "cd", "de", "ef" ]
}
{ 
   "_id" : ObjectId("559a2ebc369e4e157fe17339"), 
   "1" : [ "bc", "ab" ], 
   "2" : [ "de", "ef" ], 
   "3" : [ "aj", "kl" ]
}

你得到:

{ 
    "_id" : ObjectId("559a22f8369e4e157fe17338"),
    "intersection" : [ "cd" ]
}

一个改变的问题

个人文档如:

    { "key": 1, "value": ['ab','bc','cd']} ,
    { "key": 2, "value": ['bc','cd','de']},
    { "key": 3, "value": ['cd','de','ef']}

然后这样处理:

db.collection.aggregate([
    { "$unwind": "$value" },
    { "$group": {
        "_id": "$value",
        "keys": { "$push": "$key" },
        "count": { "$sum": 1 }
    }},
    { "$match": { "count": { "$gt": 1 } } }
])

获取单个文档中数组内数组的交集:

{
    "id": 1,
    "someKey": "abc",
    "items": [
        { "key": 1, "value": ['ab','bc','cd']} ,
        { "key": 2, "value": ['bc','cd','de']},
        { "key": 3, "value": ['cd','de','ef']}
    ]
}

然后$unwind多次处理:

db.collection.aggregate([
   { "$unwind": "$items" },
   { "$unwind": "$items.value" },
   { "$group": {
       "_id": {
          "_id": "$_id",
          "value": "$items.value" 
       },
       "keys": { "$push": "$items.key" },
       "count": { "$sum": 1 }
   }},
   { "$match": { "count": { "$gt": 1 } } }
])