gcw
gcw

Reputation: 1621

MongoDB query - Filter array by odd size

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.

Upvotes: 2

Views: 1452

Answers (2)

sheilak
sheilak

Reputation: 5873

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.

Upvotes: 4

s7vr
s7vr

Reputation: 75914

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 ] } } }
)

Upvotes: 5

Related Questions