How do I query for item with non-empty array with mongoid?

mongodb query to find non empty array
mongodb find empty array
mongodb aggregation check if array is empty
mongodb not empty string
mongodb filter array
mongodb reduce array of objects
find mongodb records where array field is empty
mongodb array has items

I have the following code that works as expected:

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

However, I would like to perform the query to return questions with related_questions array greater than 0. For example,

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

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

You can use the $size operator to query by array sizes. 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'm not familiar with Mongoid, but I found an example using $size in this documentation.

Two caveats with $size are that it cannot utilize an index (other parts of the query certainly can) and it cannot be used in range queries. If you don't mind the additional bookkeeping, a viable option is to store the array's size in a separate field (likely indexed) and query on that any way you like.

query for item with non-empty array?, Can mongoid chain mongodb condtional operators? An alternative query to basically check if an array is not empty is: 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?

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

Using js shell

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

Using mongoid

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

You can search greater any size

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

This solve your problem

Find MongoDB records where array field is not empty?, You can use $ne(Not Equal) operator for this. To understand the concept, let us create a collection with document. The query to create a  How to match documents where all array elements match. Update operators for arrays in MongoDB filter that returns the document(s) which match this than 3 items or 3 items, all of them would be in our array., The following is a comparison between the MongoDB shell and ("er$"); var query = Query.Matches(p => p.Item MongoDB C# Driver Cheat Sheet.

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

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

This will only return a Question where the related_question_ids is no nil and not an empty array.

Conversely, you can define :related_question_ids to have a default value (:default => []) and then you only need to query for .ne (Not Equal), like so:

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

Either should work.

mongodb check for array not empty query Code Example, Get code examples like "mongodb check for array not empty query" js · '%s=%s​' % (k, v) for k, v in params.items(), ^ SyntaxError: Generator  How do I query for item with non-empty array with mongoid? PHP insert nested arrays into mongoDB; Convert [object Object] from to value; High active mongodb connections « Grouping query for mongo and rails Incremental backups from server to local machine » 43 comments reply↓ Positive Reverse. Brian 2013-08-28 17:06:53

$reduce (aggregation), Query on Embedded/Nested Documents · Query an Array · Query an Array of If the argument does not resolve to an array or null nor refers to a missing field, A valid expression that $reduce applies to each element in the input array in left-to-​right order. If input resolves to an empty array, $reduce returns initialValue . The Eq("item", BsonNull.Value) query using the FilterDefinitionBuilder.Eq() method matches documents that either contain the item field whose value is null or that do not contain the item field. The { item => undef } query matches documents that either contain the item field whose value is null or that do not contain the item field.

Query for Null or Missing Fields, The { item : null } query matches documents that either contain the item field whose value is null or that do not contain the item field. This query selects all documents in the inventory collection where the tags field holds either a string that starts with be or st or an array with at least one element that starts with be or st. See also

Find MongoDB records where array field is not empty, To find MongoDB records where array field is not empty you have documents that don't have the key, you can use below:- ME.find({ pictures:  - MongoDB - find all documents where an array / list size is greater than N

Comments
  • This definitely works, and the correct way in mongoid would be: Question.where(:related_question_ids.not => {"$size"=>0}).size
  • Kamilski81 has the actual answer to this question about Mongoid.
  • :some_relation_ids.exists => true would match the empty array []. I found the :some_relation_ids.nin => [nil, []] solution to work best to retrieve "present" (non-empty) items. It is very ugly, but a prettier solution would be a $empty/$present operator added to Mongoid, or something similar.
  • I found this solution to be better, and it's written in Mongoid not just mongo syntax.