什么样的MongoDB查询在一个数组中多次发现相同的值?



假设我在MongoDB中有这样的文档

{
    "mylist":[
        {"value": 1},
        {"value": 2},
        {"value": 3}
    ]
},
{
    "mylist":[
        {"value": 1},
        {"value": 2},
        {"value": 1}
    ]
}

如何多次查询包含"{"value": 1}"的文档?是后者吗?

最好使用 $where :

来处理JavaScript求值
db.colletion.find({
    "$where": function() {
        return this.mylist.filter(function(el) {
            return el.value == 1;
        }).length >= 1;
    }
})

或者目前在聚合中没有得到很好的处理:

db.collection.aggregate([
    { "$redact": {
        "if": { "$eq": [ { "$ifNull": [ "$value", 1 ] }, 1 },
        "then": "$$DESCEND",
        "else": "$$PRUNE"
    }},
    { "$redact": {
        "if": { "$gt": [{ "$size": "$mylist" }, 1 ] },
        "then": "$$KEEP",
        "else": "$$PRUNE"
    }}
])

或者将来用$filter更好地处理:

db.collection.aggregate([
    { "$redact": {
        "if": {
            "$gt": [
                { "$size": { "$filter": {
                    "input": "$mylist",
                    "as": "el",
                    "cond": {
                        "$eq": [ "$$el.value", 1 ]
                    }
                }}},
                1
            ]
        },
        "then": "$$KEEP",
        "else": "$$PRUNE"
    }}
])

后一个操作符直到MongoDB的下一个版本才可用。但一般来说,您希望能够过滤并"计数"匹配的出现次数。有几种方法可以做到这一点。

您可以使用聚合管道—我建议展开数组,然后按原始文档和值分组,然后过滤,只留下计数大于1的结果。

最新更新