mongodb返回匹配表达式的数量

时间:2018-04-12 13:06:26

标签: mongodb aggregation-framework pymongo

我在集合中有很多文档我想运行聚合查询。假设示例文档如下所示

{"A":1,"B":2, "c":"x"}
{"A":3,"B":2, "c":"play"}
{"A":1,"B":2, "c":"test"}

这些文档我想运行一个OR查询,并且我想返回匹配的数量或条件。 例如,如果查询是

{"A":1, "A":3, "c":"test"}

它应该返回像

这样的结果
[
    {"A":1,"B":2, "c":"x", "count":1}
    {"A":3,"B":2, "c":"play", "count", 1}
    {"A":1,"B":2, "c":"test", "count":2}
]

1 个答案:

答案 0 :(得分:1)

您可以使用$addFields并根据指定条件评估您的值:

db.col.aggregate([
    {
        $addFields: {
            count: {
                $add: [
                    { $cond: [ { $eq: ["$A", 1] }, 1, 0 ] },
                    { $cond: [ { $eq: ["$A", 3] }, 1, 0 ] },
                    { $cond: [ { $eq: ["$c", "test"] }, 1, 0 ] },
                ]
            }
        }
    },
    {
        $match: {
            "count": { $gt: 0 }
        }
    }
])