2

Is it possible to build a query filter for documents with an array with odd size instead of this?

db.records.find({'$or': [{'my_array': {'$size': 1}},
                         {'my_array': {'$size': 3}},
                         {'my_array': {'$size': 5}},
                                     ...
                         {'my_array': {'$size': 15}}]}))

The filter may not catch all the items if you stop at a certain number.

2
  • What's your MongoDB server version? Commented Mar 20, 2017 at 14:24
  • The version is 3.0.7 @chridam . Commented Mar 20, 2017 at 14:29

2 Answers 2

5

You can use below aggregation query to $project the size and data field and use $mod function to keep documents with odd-sized array.

db.records.aggregate(
  { $project: { size:{ $size: "$my_array" }, data:"$$ROOT"} },
  { $match: { size: { $mod: [ 2, 1 ] } } }
)
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, this works. I would like to understand more this $match filter using $mod. Seems that $mod[2,1] returns 2 always. How does this filter even sizes?
You have to use mod as a filter. Take a look here docs.mongodb.com/manual/reference/operator/query/mod/#examples. For even size document change the remainder from 1 to 0.
Sorry I meant odd sizes in my previous comment. The docs link clarifies everything.
4

You could use $where to supply a Javascript expression to query:

db.records.find({ $where: "this.my_array.length % 2 == 1" })

The JavaScript expression will be processed for each document matched by the rest of the query so for performance you should try and ensure that the rest of your query is selective.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.