过滤和更新数据

时间:2019-01-17 09:00:06

标签: node.js mongodb mongoose

{
    "_id": "5c0a17013d8ca91bf4ee7885",
    "fixed": [
      {
        "from": "1970-01-01",
        "to": "1970-01-02",
        "isCompleted": true
      },
      {
        "from": "2017-04-18",
        "to": "2017-04-23",
        "isCompleted": false
      },
      {
        "from": "2018-01-29",
        "to": "2018-01-30",
        "isCompleted": false
      }
    ]
  },
  {
    "_id": "5c0a17013d8ca91bf4ee7886",
    "fixed": [
      {
        "from": "1970-01-01",
        "to": "1970-01-02",
        "isCompleted": true
      },
      {
        "from": "2017-04-18",
        "to": "2017-04-23",
        "isCompleted": false
      },
      {
        "from": "2018-01-29",
        "to": "2018-01-30",
        "isCompleted": false
      }
    ]
  },
  {
    "_id": "5c0a17013d8ca91bf4ee7887",
    "fixed": [
      {
        "from": "2019-04-15",
        "to": "2019-04-25",
        "isCompleted": false
      },
      {
        "from": "2017-04-18",
        "to": "2017-04-23",
        "isCompleted": false
      },
      {
        "from": "2018-01-29",
        "to": "2018-01-30",
        "isCompleted": false
      }
    ]
  }

我的数据库中有这种类型的数据,我想将isCompleted更新为false。使用日期这样的过滤器:

find({
  fix: {
    $not: {
      $elemMatch: {
        from: {
          $lt: "1970-01-02"
        },
        to: {
          $gt: "1970-01-01"
        },
        "isCompleted": true
      }
    }
  }
})

通过此查询,我得到了对象,但如何将给定日期的isCompleted设置为false,如下所示:1970-01-01和1970-01-02

这是工作示例:https://mongoplayground.net/p/WIoZZ5k0Myu

1 个答案:

答案 0 :(得分:0)

findAndModify可以解决您的问题。下面只是一个伪代码。

db.collection.findAndModify({
    query: {  from: {$lt: "1970-01-02"}  },
    update: { isCompleted: true },
    upsert: true
})