3

I have a Mongo DB with the following object:

"clients" : {
    "x" : {
        "clientId" : "x1",
        "mainInfo" : {
                       ...
        },
        "events" : 
            {
            "58a176bbc3588410cd5450c6" : {
                "clientType" : "5001",
                "location" : "60001"
                }
            "58a176bbc3588410cd5450c8" : {
                "clientType" : "5001",
                "location" : "60002"
                }
                  ....}

I cannot seem to figure out how to query where 'clients.x.events.(variable id).clientType' = 50001. Is there a way to drill down inside the events embedded object to get all records matching "clientType" : "5001"?

Thank you

  • Unfortunately that's not possible. Consider converting the `events` field to an array, querying would thus be much easier. – chridam Feb 13 '17 at 14:07

2 Answers2

0

You need to create the key value pair object like below.

var variable_id = <your variable id>;
db.collection.find({ [ 'clients.x.events.'+variable_id+'.clientType' ]:5001 });

Read more about this here

Community
  • 1
  • 1
Dau
  • 8,578
  • 4
  • 23
  • 48
0

Maybe you can use $where operator.It works for me.

Use the $where operator to pass either a string containing a JavaScript expression or a full JavaScript function to the query system.

db.collection.find({"$where" : function(){ 
    for( var c in this ){
        if( c == "x" ){ 
            for(var i in this[c]){ 
                 for(var j in this[c][i]){
                      if(j == 'clientType' && this[c][i][j] == '5001'){
                           return true;
                      }
                 }
             }
        };
     }
     return false; 
}});

Hope this helps.

McGrady
  • 10,869
  • 13
  • 47
  • 69