remove documents with array field's size less

2019-03-30 03:11发布

问题:

i have a mongoDB collection named col that has documents that look like this

{
  {
    intField:123,
    strField:'hi',
    arrField:[1,2,3]
  },

  {
    intField:12,
    strField:'hello',
    arrField:[1,2,3,4]
  },

  {
    intField:125,
    strField:'hell',
    arrField:[1]
  }
}

Now i want to remove documents from collection col in which size of the array field is less than 2.

So i wrote a query that looks like this

db.col.remove({'arrField':{"$size":{"$lt":2}}})

Now this query doesnt do anything. i checked with db.col.find() and it returns all the documents. Whats wrong with this query?

回答1:

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.



回答2:

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.



回答3:

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