Mongodb查询以查找数组中包含重复字段的所有文档

时间:2021-04-08 03:26:00

标签: mongodb aggregation-framework

    "_id" : ObjectId("0fffa133x"),
    "properties" : [ 
        {
            "key" : "1",
            “value” : “a”    
        }, 
        {
            "key” : “1”,
            “value” : “b”
        },...
    ]},
    { "_id" : ObjectId("0fffa132x"),
    "properties" : [ 
        {
            "key" : "1",
            “value” : “a”    
        }, 
        {
            "key” : “2”,
            “value” : “b”
        },...
    ]},....
   ]

我对 mongodb 比较陌生,所以我在这个查询上遇到了麻烦。基本上,我需要一个 mongodb 查询来返回属性数组包含重复键的所有文档。例如,上面的查询应该返回 id 为 0fffa133x 的文档,因为 key:1 在数组中出现了两次。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

解决方案 #1:如果您使用的是旧版本的 MongoDB

db.collection.aggregate([
    {
        $addFields: {
            pSize: { $size: "$properties" }
        }
    },
    {
        $addFields: {
            uniqueKeys: {
                $reduce: {
                    input: "$properties",
                    initialValue: [{ $arrayElemAt: ["$properties.key", 0] }],
                    in: {
                        $setUnion: ["$$value", ["$$this.key"]]
                    }
                }
            }
        }
    },
    {
        $match: {
            $expr: {
                $ne: ["$pSize", { $size: "$uniqueKeys" }]
            }
        }
    },
    {
        $project: { "pSize": 0, "uniqueKeys": 0 }
    }
]);

解决方案#2:如果您使用的是 MongoDb 版本 >= 4.4

db.collection.aggregate([
    {
        $addFields: {
            pSize: { $size: "$properties" }
        }
    },
    {
        $addFields: {
            uniqueKeys: {
                $reduce: {
                    input: "$properties",
                    initialValue: { $first: [["$properties.key"]] },
                    in: {
                        $setUnion: ["$$value", ["$$this.key"]]
                    }
                }
            }
        }
    },
    {
        $match: {
            $expr: {
                $ne: ["$pSize", { $size: "$uniqueKeys" }]
            }
        }
    },
    {
        $unset: ["pSize", "uniqueKeys"]
    }
]);

输出:

{
    "_id" : ObjectId("606f4794bc7414255cc3d49c"),
    "properties" : [
        {
            "key" : "1",
            "value" : "a"
        },
        {
            "key" : "2",
            "value" : "b"
        },
        {
            "key" : "1",
            "value" : "c"
        }
    ]
}

collection 中的测试数据:

[
    {
        properties: [
            { key: "1", value: "a" },
            { key: "2", value: "b" },
            { key: "1", value: "c" }
        ]
    },
    {
        properties: [
            { key: "1", value: "a" },
            { key: "2", value: "b" }
        ]
    }
]
相关问题