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

发布于 2025-01-14 10:17:46 字数 516 浏览 0 评论 0 原文

我想在一个查询中更改多个文档的字段类型。

这是一些示例数据。第一个示例不可扩展,如果 person1 有多个 thing1 怎么办?

这:

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

应该是:

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

我需要对数百个文档执行此操作,并且不仅仅是 thing1,还有诸如 thing2thing3、< code>thing4 等。我该怎么做?

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?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晚风撩人 2025-01-21 10:17:47

对于将“thing1”转换为数组,这里有一个选项:

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

解释:

在更新操作中使用聚合管道(mongodb 4.2+)将字段替换为数组

游乐场

For "thing1" to convert to array here is an option:

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

Explained:

Replace the field with array using aggregation pipeline( mongodb 4.2+ ) in the update operation

playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文