我的数据库架构如下所示:

[
  {
    title: {
      de: "Test",
      en: "test"
    },
    infos: [
      {
        label: {
          de: "Test",
          en: "test"
        },
        data: [
          {
            label: {
              de: "Test",
              en: "test"
            }
          },
          
        ],
        
      }
    ],
    
  }
]

如果我在模型中使用$PROJECT([]),那么对于对象来说一切都很好,所以结果是:

标题:使用以下投影时的‘测试’:

{title: `$title.de`,}

但对于对象数组,它只是将所有对象合并到一个数组中,如下所示:

    "infos": [
        {
            "label": [
                "Preparation",
                "Important"
            ]
        }
    ]

使用此投影时:

'infos.label': `$infos.label.de`

嵌套数组也是如此.

但结果应该是这样的:

{
 infos: [
  {
    label: 'Test',
    data: [
     {
       label: 'Test'
     },
    ],

  }
 ]
}

有没有人知道怎么把这样的东西存档?

推荐答案

您只需使用$map来迭代数组并相应地更改它,如下所示:

db.collection.aggregate([
  {
    $project: {
      title: "$title.de",
      infos: {
        $map: {
          input: "$infos",
          in: {
            $mergeObjects: [
              "$$this",
              {
                label: "$$this.label.de"
              }
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

Mongodb相关问答推荐

MongoDB:子文档中仅存在于父文档中的返回字段?

如何在MongoDB中查找和过滤嵌套数组

如何使用MongoDB对子文档进行条件投影?

字段$set聚合导致错误美元($)前缀字段$concatArrays对于存储无效"

如何用Python和MongoDB找到单据字段的最大值?

从 Amazon S3(Next.js、Mongodb、Mongoose)删除图像

使用特定关键字和邻近度进行查询和过滤

定期自动轮换 MongoDb 集合

如何在 MongoDB 中已经存在的 slug 中添加一个随机数?

如何过滤查找mongodb的结果

将 MongoDB 转移到另一台服务器?

pymongo 排序和 find_one 问题

适用于 Windows 10 64 位的 MongoDB 下载

MongoDB count() 未定义

如何在 Rails 中混合使用 mongodb 和传统数据库?

Mongoid 不在查询中

试图从 mongoose 获取Collection 列表

带有条件的MongoDB聚合查找

MissingSchemaError:Schema hasn't been registered for model

MongoDB Compass:select distinct field values