MongoDB查询,如果值不为空,则更新特定字段



我有一个对象"input">,将像参数一样传递给查询:

var input = {
id: 1,
componentId: x,
commands: [...],
user: [...],
}

集合"testCollection">

testCollection = {
id: 1,
model: {
stepComponents: [
{  
componentId: x
command: [...],
user: [...],
}
]
}
}

我的问题是如何更新"testCollection">上的特定字段,如果它未定义或为空,则跳过更新。这意味着,如果"input.user">未定义/为null,则不更新的"user"字段。

更新查询示例如下:

testCollection.update(
{
_id: objectId(input.id),
'model.stepComponents.componentId': input.componentId
},
{
'inputs': input.inputs,
'model.stepComponents.$.commands': input.commands,
'model.stepComponents.$.users': input.users,
},
{ upsert: true },
);

如有任何帮助,我们将不胜感激。谢谢

我也遇到了同样的问题,并通过以下解决方案解决了问题

let params= {
id: req.body.id, componentId: req.body.x, commands: req.body...,
}
;
for(let prop in params) if(!params[prop]) delete params[prop];//it will remove fields who are undefined or null 
testCollection.findOneAndUpdate( {
_id: req.params.id
}
, params);

试试这个:

testCollection.update(
{
_id: objectId(input.id),
user: {$ne: null}
},
{
$set: {input}
}

);

您可以尝试使用现有的

db.collection.find({ "fieldToCheck": { $exists: true, $ne: null } })

最新更新