如何使用一个变量作为字段名在 mongodb-本机 findOne() ?

我在蒙哥德有这个数据:

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

并且我希望在查询中将字段名作为变量传递时检索数据。

以下内容不起作用:

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

如何保持字段名及其值是动态的?

72088 次浏览

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.

I'd like to clarify that if you're trying to make a query concerning a nested field only (not its value), like if you want to query the field "name" from this document:

{
loc: [0, 3],
unit: {
name : "playername"
}
}

this will work (as in my case - using update):

mdb.cords.updateOne(
{_id: ObjectID(someid)},
{$set: {[query]: newValue}},
function (err, result) {
...
}
}

Simply enclosing [query] in brackets tells mongodb that it's not literal, but rather a path.

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);
});

use like this if the object is nested.

Direct Object:-

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

An object is nested:-

var surname=req.params.surname;
var value = req.params.value;
var condition = `name.${surname}`
collection.findOne({[condition]:value}, function(err, item) {
res.send(item);
});