user2521119
user2521119

Reputation: 165

MongoDB: querying using a string reference as a key

Does anyone know if there's a way to use a reference to a string in a mongo query, instead of using the string directly in it?

i.e. I want to do this:

key = "id";
value = "12345";
collection("accounts").find({key: value});

Instead of this:

collection("accounts").find({"id": "12345"});

Upvotes: 0

Views: 556

Answers (1)

chridam
chridam

Reputation: 103425

Use the bracket notation to create the query object:

key = "_id";
value = "57ffe131b0b79719a0db75d8";
query = {};
query[key] = ObjectId(value);
collection("accounts").find(query);

Upvotes: 1

Related Questions