skip to Main Content

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


  1. you can use the dot notation with a wildcard to match any family member:

    db.collection.find({"family_member.$*.address.state": "Hawaii"})
    

    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!

    Login or Signup to reply.
  2. 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.

    db.collection.aggregate([
      {
        "$project": {
          "family_member": {
            "$arrayToObject": [
              {
                "$filter": {
                  "input": {
                    "$objectToArray": "$family_member"
                  },
                  "as": "member",
                  "cond": {
                    $eq: [
                      "$$member.v.address.state",
                      "Hawaii"
                    ]
                  }
                }
              }
            ]
          }
        }
      }
    ])
    

    Outputs

    [
      {
        "family_member": {
          "brother": {
            "address": {
              "city": "Honolulu",
              "state": "Hawaii",
              "zip_code": "96813"
            },
            "age": 13,
            "name": "Jordan"
          }
        }
      }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search