Unable to find value using variable as field name in find() method within Mongo Shell

313 Views Asked by At

I've executed the following command in mongo shell:

db.perscoll.insert({CT:{English:{genre:[{name:varGenre}]}}})

Now, i want to find whether genre for 'English' exists in the collection or not using find(), which will return either 0(false) or 1(true).

db.perscoll.find({'CT.English.genre.name':varGenre}).count();

The above command returns me 1(true), but when i try to execute the same command using variable as mentioned below, it returns 0 .

var eType = 'CT';
var lang = 'English';
var varGenre = 'Action';
var gnrNameChk = {}; 
gnrNameChk[eType+'.'+lang+'.genre.name'] = ''; 
print(gnrNameChk);
db.perscoll.find({gnrNameChk:varGenre}).count();

What can be the problem? how to tackle this? I'm not getting any way to sort this out.

1

There are 1 best solutions below

0
On

Try the following: var eType = 'CT'; var lang = 'English'; var varGenre = 'Action'; var gnrNameChk = {}; gnrNameChk[eType+'.'+lang+'.genre.name'] = varGenere; print(gnrNameChk); db.perscoll.find(gnrNameChk).count();

Hope that helps you!!!