Start a new topic

How to query object in object with dynamic query string?


I'm trying to find objects in objects stored in a collection. An object looks like this:


  "GNJB5B4": {

    "title": "some text",

    "rating": 2


  "GNF3CHA": {

    "title": "some text",

    "rating": 5



Let's assume I have stored this object in collection mycollection and there in column mylist.

I would like to know which records have an entry with key "GNJB5B4". Reading in MongoDBs documentation I could find a solution:

modules.collectionAccess.collection('mycollection').find({ "mylist.GNJB5B4" : { $exists : true } },   
   function (err, entries){ (entries.length);

This works like a charm and outputs the amount of records in mycollection with the given entry in mylist.

I now want to set the search key ("mylist.GNJB5B4")  by a variable like:

var searchString = 'mylist.' + 'GNJB5B4';
modules.collectionAccess.collection('mycollection').find({searchString : { $exists : true } },   
   function (err, entries){ (entries.length);

In this case the output is always: 


Conclusion: As soon as I try to replace a static search value by a variable value the result is "undefined".

Any idea/solution how to fix that?


My bad, found the solution, it's rather a Javascript specific problem: 

For simple keys stored in variables you could use [key]

For dotted keys like in my case (mylist.key) you have to define the object in an official way, then it works. Based on my example above:   

var mylist = {};
mylist[<set searchkey here>] = '';

modules.collectionAccess.collection('mycollection').find({ mylist : { $exists : true } }, function (err, entries){ 

It is important, that the object variable  ("mylist" in my example)  has the same name as the column name of the collection that holds the object! Maybe there is a better solution but this works.


I was wrong. The query above will return ALL records (whether search key is in record or not). After trying a lot I found out you have to define the whole query this way:   

  var mylist = {};
  mylist['<column of collection>.' + <search key here>] = { $exists : true };

  modules.collectionAccess.collection('mycollection').find(mylist, function (err, entries){ ...


That works and will return the expected result.

Sorry for that and Regards

Login or Signup to post a comment