将嵌入属性重写为所有文档的顶级字段

时间:2018-06-08 09:44:57

标签: mongodb mongodb-query

我的结构看起来或多或少像这样:

{
   "_id": "xxx",
   "pubDate": {
     "dateTime": ISODate("2018-05-09T10:00:45.0Z"),
     "offset": "Z",
     "zone": "Z"
  }
}

如何将嵌套对象中的pubDate.dateTime更改为pubDate

{
   "_id": "xxx",
   "pubDate": ISODate("2018-05-09T10:00:45.0Z")
}

1 个答案:

答案 0 :(得分:1)

使用bulkWrite()分两步和$rename更新修饰符:

db.collection.bulkWrite([
  { "updateMany": {
    "filter": { },
    "update": {
      "$rename": { "pubDate.dateTime": "tmpDate" }
    }
  }},
  { "updateMany": {
    "filter": { },
    "update": {
      "$rename": { "tmpDate": "pubDate" }
    }
  }}
])

这是重写所有字段的最快方法。您需要两个步骤,因为当内部已经存在某个属性时,您不能只将一个级别写为pubDate