Search code examples
mongodb-querynode-mongodb-native

Using Dynamic strings for querying nested mongo doc


I'm using the dot notation for querying a nested mongo doc. However I want this query to be dynamically generated.

For eg The nesting is as

{ "Car":
     {
       "Make":
              { "Model": "Some val"
                 Year  : "Some year"
               }
     }
}

If I perform a query like db.carcoll.find({'Car.Make.Model':'some val'}) I get the results. However this query string 'Car.Make.Model' could change to be Car.Make.Year and I like this query to be dynamic.

I set it in a variable and try something like query='Car.Make' + choice; where choice is a variable its either ".Model" or ".Year"

and run db.carcoll.find({query:"1989"})

I don't get the results in this case. How do I handle this


Solution

  • Not tested it, just thoughts. Did you tried this code:

     var prop = "Car.Make." +  "Model" //or ""Year"
    var query = {};
    query[prop] = "1989";
    db.carcoll.find(query)