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

时间:2018-11-30 04:45:22

标签: mongodb mongodb-query

我有一个对象“输入” ,它将像参数一样传递给查询:

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

和集合“ testCollection”

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

我的问题是如何更新“ testCollection” 上的特定字段,如果未定义或为空,则跳过该更新。 这意味着如果“ input.user” 未定义/为空,则不会更新“ 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 },
);

任何帮助将不胜感激。谢谢。

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

尝试这个:

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

);

答案 2 :(得分:0)

您可以尝试使用exists

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