Friday, 11 October 2019

mongo serach in array, and update

Search in array.

if you have:
you can do search people who have friends age in 20 and female, like this:

db.getCollection('people').find( { "friends.age": "20" , "": "girl"  })

however above query will give you all people who has friends with 20 or sex is girl which means it gives you people if it has female friend or it has friends in 20.

but what we want is people who has friends sex in female and 20.

in this case you have to use $elemMatch

db.getCollection('people').find( { "friends" : { elemMatch {"age": "20" , "sex": "girl"  }}})


if you just want to update the first element, then you can use $ which will update the first item.

you can find example here:

   { { "friends" : { $elemMatch {"age": "20" , "sex": "girl"  }}} },
   { $set: { "friends.$.flag" : "hasboyfriend" } }

you can then use the first girl in the list and chose this girl as this people's gril friend and mark this girl as "hasboyfriend".

however, you may want to update all girls. then you need to use: $[<identifier>]  and updateMany

$[<identifier>] will make sure all grils in a selected people are updated.

updateMany will make sure all selected people will be updated.[%3Cidentifier%3E]

1. query just query(the first find filter) people .
2. but if you want to update friends (array) , and not all friend, you need to use  "arrayFilters" to filter which friends you want to update.
3. and then use $set and $[<identifier>] to update.

good example:

then you may ask that i was using $elemMatch in find filter, should i use it again in arrayfilters if i have multi filters?

answer is no, example:

more complex example to update further nested array:

1 comment: