简体   繁体   English

mongodb 将多个文档的字段类型改为数组

[英]mongodb change field type of several documents to array

I want to change the field type of several documents in one query.我想在一个查询中更改多个文档的字段类型。

This is some example data.这是一些示例数据。 The first example isn't scalable, what if person1 has more than one thing1 ?第一个示例不可扩展,如果 person1 有多个thing1怎么办?

This:这个:

{ "name": "person1", "things": { "thing1": { "thingInstanceID": 400 } } }

should be:应该:

{ "name": "person1", "things": { "thing1": [{ "thingInstanceID": 400 }] } }

I need to do this with hundreds of documents, and there's more than just thing1 , something like thing2 , thing3 , thing4 , etc. How can I do this?我需要对数百个文档执行此操作,而且不仅仅是thing1 ,还有thing2thing3thing4等。我该怎么做?

For "thing1" to convert to array here is an option:对于将“thing1”转换为数组,这里有一个选项:

 db.collection.update({},
 [
  {
    $addFields: {
      "things": {
         thing1: [
          "$things.thing1"
         ]
       }
     }
   }
])

Explained:解释:

Replace the field with array using aggregation pipeline( mongodb 4.2+ ) in the update operation在更新操作中使用聚合管道(mongodb 4.2+)将字段替换为数组

playground操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM