【问题标题】:MongoDB Query, update specific field if value is not nullMongoDB查询,如果值不为空,则更新特定字段
【发布时间】:2019-05-02 05:54:57
【问题描述】:

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

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

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

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案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);
    

    【讨论】:

    • 对不起,我的回复晚了,它解决了我的问题,谢谢。
    【解决方案2】:

    试试这个:

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

    );

    【讨论】:

    • 不适合我的情况,anw,谢谢你的帮助:)
    【解决方案3】:

    你可以尝试使用exists

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

    【讨论】:

      猜你喜欢
      • 2014-03-31
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      相关资源
      最近更新 更多