gpt4 book ai didi

ruby - Mongoid:根据嵌入文档数组的大小进行查询

转载 作者:IT老高 更新时间:2023-10-28 13:32:35 27 4
gpt4 key购买 nike

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

MongoDB query based on count of embedded document

假设我有 客户:{_id: ...,订单:[...]}

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

最佳答案

我更好的方法是使用 MongoDB 的 native 语法,而不是像您链接到的问题的已接受答案中所指出的那样诉诸方法或 JavaScript 评估之类的轨道。尤其是评估 JavaScript 条件会慢得多。

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

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 个或更多成员。

还请注意,这些条件都不能单独作为一个索引,因此如果您有另一个过滤点,最好先包含该条件。

关于ruby - Mongoid:根据嵌入文档数组的大小进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25538829/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com