I have a collection which has one of the fields in it as a nested dictionary.
Sample:
{
"_id": ObjectId(""),
"family_member": {
"mother":{
"name": "Mary",
"age": 40,
"address": {
"city": "Dover",
"state": "Delaware",
"zip_code": "19901"
}
},
"father":{
"name": "John",
"age": 43,
"address": {
"city": "Dover",
"state": "Delaware",
"zip_code": "19901"
}
},
"brother":{
"name": "Jordan",
"age": 13,
"address": {
"city": "Honolulu",
"state": "Hawaii",
"zip_code": "96813"
}
}
}
}
I want to get a list of the documents where any of the family member resides in Hawaii. Basically something like:
db.users.find({'family_member.*.address.state': "Hawaii"})
.
Is something like this even possible or do I have to write multiple match conditions?
2
Answers
you can use the dot notation with a wildcard to match any family member:
This will return all documents where any family member’s address state is "Hawaii". However, note that this syntax is only supported in MongoDB 4.4 and above.
I hope this helps!
You will need to use the aggregation framework to match subdocuments for different fields.
In your case, you can convert the object to an array, filter for your condition and convert back to objects.
Outputs