查询过滤器:数组属性长度小于另一个属性的值

时间:2014-10-05 18:37:11

标签: mongodb

模式

{
useLimit: Number,
uses: [{...}]
}

我想查询此集合仅匹配使用长度小于useLimit或useLimit为-1(表示无限)的文档

1 个答案:

答案 0 :(得分:0)

执行此操作的一种方法是在$where查询中使用find()运算符:

// pass a function to the `$where` operator, to pick records 
// if they meet the desired condition. 
db.collection.find( {
    $where : function() {
        return (this.uses.length < this.useLimit || this.useLimit == -1);
    }
})

或使用aggregation管道

  • 为每个文档投放一个字段isValid,其值已解析 到truefalsetrue,如果符合条件,则为false
  • 下一步是将所有文件与isValid匹配 属性值为true
  • 最后,$project运算符投影除了以外的字段 isValid

如下,

db.collection.aggregate( [ {
    $project : {
        "uses" : 1,
        "useLimit" : 1,
        "isValid" : {
            $cond : [ {
                $or : [ {
                    $gte : [ "$useLimit", {
                        $size : "$uses"
                    } ]
                }, {
                    $eq : [ "$useLimit", -1 ]
                } ]
            }, true, false ]
        }
    }
}, {
    $match : {
        "isValid" : true
    }
}, {
    $project : {
        "uses" : 1,
        "useLimit" : 1
    }
} ])
相关问题