Reputation: 1640
I have this document in Mongo
{
"_id" : "hxQee6xCQSD9C9Qok",
"bank_account" : {
"12345" : {
"account" : "12345",
"type" : "bank_account"
}
}
}
I want to run a query against mongoDB, I know I can do this
db.donate.find({'bank_account.12345.account': '12345'})
But what I would like to do is use a variable to search for the account number, '12345' So I've tried this
var bankNumber = '12345';
var accountLookup = {bank_account[bankNumber]account: bankNumber};
var obj = db.donate.findOne(accountLookup);
and I get this error
Error: Line 2: Unexpected token [
If I wrap this in quotes it doesn't work either. How can I format my query to lookup either by the object '12345' or by the account property '12345'?
Upvotes: 0
Views: 567
Reputation: 311875
Assemble your query key programmatically:
var bankNumber = '12345';
var accountLookup = {};
accountLookup['bank_account.' + bankNumber + '.account'] = bankNumber;
var obj = db.donate.findOne(accountLookup);
Upvotes: 1