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

Kam*_*i81 6 ruby mongodb mongoid

我有以下代码按预期工作:

Mongoid::Criteria.new(Question).where(:related_question_ids.size => 0)
Run Code Online (Sandbox Code Playgroud)

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

Mongoid::Criteria.new(Question).where(:related_question_ids.size.gte => 0)
Run Code Online (Sandbox Code Playgroud)

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

jmi*_*ola 2

您可以使用$size 运算符按数组大小进行查询。考虑以下使用 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, "x" : [ 1, 2 ] }
{ "_id" : 3, "x" : 3 }
Run Code Online (Sandbox Code Playgroud)

我不熟悉 Mongoid,但我$size本文档中找到了一个使用的示例。

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

  • 这绝对有效,mongoid 中的正确方法是: Question.where(:lated_question_ids.not => {"$size"=>0}).size (8认同)