Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb $elemMatch query inside map

I need to search inside a map element with a certain value in mongodb.

I have this element in data base:

{
  "_id": ObjectId("52950e93c4aad399cff0d9f9"),
  "_class": "com.company.model.customer.DbCustomer",
  "version": NumberLong(0),
  "channels": {
    "adea3d4e-2a73-4f3e-8a89-a336d6132909": {
      "value": "[email protected]",
      "alias": "email1",
      "deliveryChannel": "EMAIL",
      "status": "GOOD",
      "_class": "com.company.model.customer.CustomerEmail"
    }
  }
}

Where "adea3d4e-2a73-4f3e-8a89-a336d6132909" is a key of a map of channels.

What I want to search is a channel with certain value.

If "channels" were an array the query would be this way:

{ "channels" : 
  { "$elemMatch" : { "value" : "[email protected]" } }
}

But, as channels is a map, I can't use this approach.

Is it possible to search inside a map the same way you search inside an array?

Notice that I want to use a single query, for security reasons I cannot use the map reduce functionality in my database.

Thanks in advance.

like image 994
pg22 Avatar asked Jul 10 '26 18:07

pg22


1 Answers

Your sample code does not contain an array which have to look like [1, 2, 3].

Therefore you have to search in a sub-field like the following example:

db.Collection.find({"channels.value" : "[email protected]"})

Hope this will help.....

like image 116
nish71 Avatar answered Jul 13 '26 22:07

nish71



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!