加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何使用mongoid查询非空数组的项?

发布时间:2020-12-17 03:22:13 所属栏目:百科 来源:网络整理
导读:我有以下代码按预期工作: Mongoid::Criteria.new(Question).where(:related_question_ids.size = 0) 但是,我想执行查询以返回related_questions数组大于0的问题.例如, Mongoid::Criteria.new(Question).where(:related_question_ids.size.gte = 0) 有没有办
我有以下代码按预期工作:

Mongoid::Criteria.new(Question).where(:related_question_ids.size => 0)

但是,我想执行查询以返回related_questions数组大于0的问题.例如,

Mongoid::Criteria.new(Question).where(:related_question_ids.size.gte => 0)

有没有办法用mongoid或mongodb做到这一点?

解决方法

您可以使用 $size operator按数组大小进行查询.请考虑使用JS shell的以下示例:

> db.foo.drop()
> db.foo.insert({_id: 1,x:[1,2]});
> db.foo.insert({_id: 2,x:[]});
> db.foo.insert({_id: 3,x:3});

> db.foo.find({x: {$size: 0}})
{ "_id" : 2,"x" : [ ] }

> db.foo.find({x: {$size: 1}})

> db.foo.find({x: {$size: 2}})
{ "_id" : 1,"x" : [ 1,2 ] }

> db.foo.find({x: {$not: {$size: 2}}})
{ "_id" : 2,"x" : [ ] }
{ "_id" : 3,"x" : 3 }

> db.foo.find({x: {$not: {$size: 0}}})
{ "_id" : 1,2 ] }
{ "_id" : 3,"x" : 3 }

我对Mongoid不熟悉,但我在this documentation找到了一个使用$size的例子.

$size的两个警告是它不能使用索引(查询的其他部分当然可以)并且它不能用于范围查询.如果你不介意额外的簿记,一个可行的选择是将数组的大小存储在一个单独的字段中(可能是索引的)并以任何你喜欢的方式查询.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读