How can I request an element with a non-empty array with mongoid?

I have the following code that works as expected:

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

However, I would like to execute a query to return questions with an array of related_questions greater than 0. For example,

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

Is there a way to do this with a mangoid or mongodb?

+5
source share
3 answers

You can use the $ size operator to query for the size of the array. Consider the following example using the 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 } 

I am not familiar with Mongoid, but I found an example using $size in this documentation .

Two caveats with $size are that it cannot use an index (possibly other parts of the query), and it cannot be used in range queries. If you do not mind additional bookkeeping, a viable option is to save the size of the array in a separate field (probably indexed) and query it in any way.

+2
source

This query search, if any object exists in the related_question_ids field [0]

Using js shell

db.questions.find("related_question_ids.0": {exists => true} )

Use of mangoid

Mongoid::Criteria.new(Question).where(:"related_question_ids.0".exists => true)

You can search more than any size

Mongoid::Criteria.new(Question).where(:"related_question_ids.3".exists =>true)

This will solve your problem.

+3
source

Another way to do this is to use the .nin (Not IN) request form:

 Mongoid::Criteria.new(Question).where(:related_question_ids.nin => [nil,[]]) 

This will only return the question where related_question_ids is not nil and not an empty array.

Conversely, you can define :related_question_ids have a default value ( :default => [] ), and then you only need to request .ne (not equal), for example, like this:

 Mongoid::Criteria.new(Question).where(:related_question_ids.ne => []) 

Or it should work.

0
source

All Articles