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" , "friends.sex": "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"  }}})




https://studio3t.com/knowledge-base/articles/filter-elements-from-mongodb-arrays/


update:

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

you can find example here:

https://docs.mongodb.com/manual/reference/operator/update/positional/

db.people.updateOne(
   { { "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.


https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#up._S_[%3Cidentifier%3E]


https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/
https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/#db.collection.updateMany




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:
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#update-all-documents-that-match-arrayfilters-in-an-array

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:

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#update-all-array-elements-that-match-multiple-conditions


more complex example to update further nested array:

https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#update-nested-arrays-in-conjunction-with

1 comment: