Mongoid:基于嵌入式文档数组的大小查询

瑟夫

这类似于这里的问题,但我不知道如何将其转换为Mongoid语法:

基于嵌入式文档计数的MongoDB查询

假设我有 Customer: {_id: ..., orders: [...]}

我希望能够找到具有现有订单(即orders.size> 0)的所有客户。我尝试了Customer.where(:orders.size.gt => 0)无济于事的查询可以由exists?操作员来完成吗?

尼尔·伦恩

我更好的方法是使用MongoDB的本机语法,而不是诉诸于链接到的问题的可接受答案中指出的方法或JavaScript评估之类的方法。特别是在评估JavaScript条件时,速度会慢得多。

$exists对于长度大于零的数组,其逻辑扩展是使用“点表示法”并测试是否存在“零索引”或数组的第一个元素:

Customer.collection.find({ "orders.0" => { "$exists" => true } })

看来可以使用任何索引值至少n-1等于要测试的数组“长度”的索引值来完成

值得注意的是,对于“零长度”数组排除$size,当与$not否定匹配项时,运算符也是有效的替代方法

Customer.collection.find({ "orders" => { "$not" => { "$size" => 0 } } })

但这不适用于较大的“尺寸”测试,因为您需要指定要排除的所有尺寸:

Customer.collection.find({ 
    "$and" => [ 
        { "orders" => { "$not" => { "$size" => 4 } } }, 
        { "orders" => { "$not" => { "$size" => 3 } } },
        { "orders" => { "$not" => { "$size" => 2 } } },
        { "orders" => { "$not" => { "$size" => 1 } } },
        { "orders" => { "$not" => { "$size" => 0 } } }
    ]
})

因此,其他语法更加清晰:

Customer.collection.find({ "orders.4" => { "$exists" => true } })

简洁地表示5个或更多成员。

另请注意,仅这些条件中的任何一个都不能仅作为索引,因此,如果您有另一个过滤点,则最好首先包括该条件。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章