Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 680
lovesh Avatar asked May 03 '12 21:05

lovesh


2 Answers

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.

like image 56
JohnnyHK Avatar answered Nov 15 '22 07:11

JohnnyHK


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.

like image 39
Sean Reilly Avatar answered Nov 15 '22 07:11

Sean Reilly