首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >图像更改模式的孟戈db数组

图像更改模式的孟戈db数组
EN

Stack Overflow用户
提问于 2022-06-04 16:10:54
回答 1查看 31关注 0票数 0

我在mongodb中有一个图像数组,我正在尝试更改数组的架构。现在,图像存储得像下面这样。

代码语言:javascript
复制
["https://images.freeimages.com/images/large-previews/e51/tokyo05-2-1447803.jpg","https://images.freeimages.com/images/large-previews/aae/lomo-spider-1386711.jpg","https://images.freeimages.com/images/large-previews/383/the-home-of-the-candle-1-1425911.jpg"]

我想要的最后输出就像下面一样。

代码语言:javascript
复制
[
    {
      url:
        "https://images.freeimages.com/images/large-previews/e51/tokyo05-2-1447803.jpg",
      index: "1"
    },
    {
      url:
        "https://images.freeimages.com/images/large-previews/aae/lomo-spider-1386711.jpg",
      index: "2"
    },
    {
      url:
        "https://images.freeimages.com/images/large-previews/383/the-home-of-the-candle-1-1425911.jpg",
      index: "3"
    },
]

我怎么能在mongosh做这件事?

作为Python这样做,然后导入回mongodb会更容易吗?谢谢您抽时间见我!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-05 08:44:44

由于mongoDB版本4.2+,您可以从mongosh中执行以下操作:

代码语言:javascript
复制
db.collection.update({},
[
 {
   $addFields: {
     x: {
       "$map": {
         "input": "$x",
         "as": "y",
         "in": {
           url: "$$y",
           index: {
             $indexOfArray: [
               "$x",
               "$$y"
             ]
           }
         }
       }
     }
   }
 }
],
{
  multi: true
})

解释:

  1. 通过addFields将文档中的数组x(在这里假设数组字段键为x)替换为新格式的对象数组(使用$indexOfArray生成新的“索引”字段的内容)。
  2. 添加{multi}以更新集合中的所有文档

游乐场

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72501264

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档