how to query mongodb when you list of values

Viewed 159

I am trying to find a mongodb query for the below document. Find all the documents that has this guid 360DC2AE-2B67-4E8D-E320-71D0D30D90F7 but the guid can be in 1st node or any node in the contactlists.values.

The sample below query doesn't work when the guid is in 2nd or 5th node.

db.Contacts.find( {

    "Tags.Entries.ContactLists.Values.0.Value": "{360DC2AE-2B67-4E8D-E320-71D0D30D90F7}"
}

)

{ 
"_id" : BinData(3, "ZLz5ddW2pUCpYg4R+8XWgA=="), 
"Identifiers" : {
    "IdentificationLevel" : NumberInt(2), 
    "Identifier" : "user1@gmail.com"
}, 
"Personal" : {
    "FirstName" : "user1", 
    "Surname" : "user1"
}, 
"Emails" : {
    "Preferred" : "Preferred", 
    "Entries" : {
        "Preferred" : {
            "SmtpAddress" : "user1@gmail.com"
        }
    }
}, 
"Lease" : null, 
"Tags" : {
    "Entries" : {
        "ContactLists" : {
            "Values" : {
                "0" : {
                    "Value" : "{360DC2AE-2B67-4E8D-E320-71D0D30D90F7}", 
                    "DateTime" : ISODate("2021-10-08T21:42:30.731+0000")
                }, 
                "1" : {
                    "Value" : "{4D90C25F-F0BE-47C0-EB6E-CA799B25E91B}", 
                    "DateTime" : ISODate("2021-10-08T21:52:04.355+0000")
                }, 
                "2" : {
                    "Value" : "{6DC40CA8-AC78-404C-C5D3-1E868E1D8EB4}", 
                    "DateTime" : ISODate("2021-10-08T21:52:26.156+0000")
                }
            }
        }
    }
}

}

2 Answers

Simple solution is using aggregations

  • Make the objects to array using $objectToArray
  • Check whether it has the value using $match

here is the code

db.collection.aggregate([
  {
    $addFields: {
      "objToArray": {
        "$objectToArray": "$Tags.Entries.ContactLists.Values"
      }
    }
  },
  {
    "$match": {
      "objToArray.v.Value": "{360DC2AE-2B67-4E8D-E320-71D0D30D90F7}"
    }
  },
  {
    $project: {
      objToArray: 0
    }
  }
])

Working Mongo playground

if your values is an array, use $

"Tags.Entries.ContactLists.Values.$.Value": "{360DC2AE-2B67-4E8D-E320-71D0D30D90F7}"

If it Is embedded document, you can only enumerate all.

Maybe you can try enumerate up to 100 item.

"Tags.Entries.ContactLists.Values.0.Value": "{360DC2AE-2B67-4E8D-E320-71D0D30D90F7}",
"Tags.Entries.ContactLists.Values.1.Value": "{360DC2AE-2B67-4E8D-E320-71D0D30D90F7}",
"Tags.Entries.ContactLists.Values.2.Value": "{360DC2AE-2B67-4E8D-E320-71D0D30D90F7}",
"Tags.Entries.ContactLists.Values.3.Value": "{360DC2AE-2B67-4E8D-E320-71D0D30D90F7}"
Related