Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable as a field name in mongodb-native findOne()?

I have this data in mongodb:

{       "name": "Amey",     "country": "India",     "region": "Dhule,Maharashtra" } 

and I want to retrieve the data while passing a field name as a variable in query.

Following does not work:

var name = req.params.name; var value = req.params.value; collection.findOne({name: value}, function(err, item) {     res.send(item); }); 

How can I query mongodb keeping both field name and its value dynamic?

like image 810
WillMcavoy Avatar asked Jun 11 '13 07:06

WillMcavoy


People also ask

How do I declare a variable in MongoDB?

Set variable value in MongoDB save() methodUse db. yourCollectionName. save(yourVariableName) to set variable value, wherein “yourVariableName” is your variable.

How do I search in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.

How use MongoDB $set?

The $set operator replaces the value of a field with the specified value. The $set operator expression has the following form: { $set: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.


2 Answers

You need to set the key of the query object dynamically:

var name = req.params.name; var value = req.params.value; var query = {}; query[name] = value; collection.findOne(query, function (err, item) { ... }); 

When you do {name: value}, the key is the string 'name' and not the value of the variable name.

like image 127
maxdec Avatar answered Oct 16 '22 11:10

maxdec


Just put the variable in []

var name=req.params.name; var value = req.params.value; collection.findOne({[name]:value}, function(err, item) { res.send(item); }); 
like image 25
KiwenLau Avatar answered Oct 16 '22 10:10

KiwenLau