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

无人久伴 提交于 2019-12-05 00:33:00

问题


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



回答4:


The following should work

db.col.remove({$where: "this.arrField.length < 2"})


来源:https://stackoverflow.com/questions/10439860/remove-documents-with-array-fields-size-less-than-3-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!