remove documents with array field's size less than 3 in mongoDB

With MongoDB 2.2+ you can use numeric indexes in condition object keys to do this:

db.col.remove({'arrField.2': {$exists: 0}})

This will remove any document that doesn't have at least 3 elements in arrField.


From the documentation for $size:

You cannot use $size to find a range of sizes (for example: arrays with more than 1 element).

The docs recommend maintaining a separate size field (so in this case, arrFieldSize) with the count of the items in the array if you want to try this sort of thing.


Note that for some queries, it may be feasible to just list all the counts you want in or excluded using (n)or conditions.

In your example, the following query will give all documents with less than 2 array entries:

db.col.find({
  "$or": [
    { "arrField": {"$exists" => false} },
    { "arrField": {"$size" => 1} },
    { "arrField": {"$size" => 0} }
  ]
})