更新对象数组中的字段

时间:2021-01-05 13:37:13

标签: mongodb mongodb-query

我有一个以以下形式存储文档的集合:

{
  "_id": ObjectId("..."),
  "begin": 2020-10-01,
  "dates": [
    { "name": "one", "created": 2020-10-10, "updated": 2020-10-11 },
    { "name": "two", "created": 2020-10-12, "updated": 2020-10-13 },
    ...
  ]
}

我想更新这个集合,为集合的每个文档中包含的每个日期添加 3 天。我的示例文档将变为:

{
  "_id": ObjectId("..."),
  "begin": 2020-10-04,
  "dates": [
    { "name": "one", "created": 2020-10-13, "updated": 2020-10-14 },
    { "name": "two", "created": 2020-10-15, "updated": 2020-10-16 },
    ...
  ]
}

基于 MongoDB 文档,我编写了以下查询:

db.getCollection('test').updateMany({}, [{
  $set: {
    begin: { $add: ["$begin", 3*24*60*60*1000] },
    "dates.$.created": { $add: ["$dates.$.created", 3*24*60*60*1000] },
    "dates.$.updated": { $add: ["$dates.$.updated", 3*24*60*60*1000] }
  }
}])

然而,这不起作用,因为这种访问数组中字段的语法是无效的(例如,在 $add 操作中,$dates.$.created 表示 $非法的字段名称)。

在上面的代码段中,我如何访问现有的字段值来更新它?还有别的方法吗?

1 个答案:

答案 0 :(得分:0)

您正在使用聚合管道更新,聚合将不支持 $toDate 投影更新,

  • 使用 $map 将字符串类型日期转换为 ISO 日期,如果它已经是日期类型,则删除此对话
  • dates 迭代 created 的外观,然后在 updatedlet dayPlus = 3*24*60*60*1000; db.getCollection('test').updateMany({}, [{ $set: { begin: { $add: [{ $toDate: "$begin" }, dayPlus] }, dates: { $map: { input: "$dates", in: { name: "$$this.name", created: { $add: [{ $toDate: "$$this.created" }, dayPlus] }, updated: { $add: [{ $toDate: "$$this.updated" }, dayPlus] } } } } } }] ) 字段中添加天数
child: new CircleButton(
  onTap: () {
    if(IconData==Icons.control_point){
      print("hello");
    }
  },
  iconData: _iconsDaily[index]
),

Playground