【问题标题】:Add field of array element in MongoDB aggregation在 MongoDB 聚合中添加数组元素的字段
【发布时间】:2019-10-27 14:50:50
【问题描述】:

我有一个包含对象数组的文档集合:

db.collection.insert({
    arr: [
      { id: 1, text: 'foo' },
      { id: 2, text: 'bar' },
    ]
});

有没有办法在该数组中提取/投影/添加 one 元素的字段?例如,数组第一个元素的text 字段。我在MongoPlayground 中尝试了$addFields 的各种变体,

db.collection.aggregate([
  {
      $addFields: { text1: '$arr.text' }
  }
]);

但没有生成一个text 字段。充其量,我得到了两者,使用上面的语法,但我只想要一个字段,以便在其上使用 $type,因为它显示为$type can't inspect array elements

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    提取数组元素字段的一种方法是在$project 阶段使用$arrayElemAt 投影第一个元素,然后访问所需的字段,例如text,稍后$project 阶段:

    db.collection.aggregate([
      {
        $project: {
          elem1: {
            $arrayElemAt: ["$arr", 0]
          }
        }
      },
      {
        $project: {
          text1: "$elem1.text"
        }
      }
    ])
    

    Mongo Playground.

    【讨论】:

      【解决方案2】:

      您可以使用$let$arrayElemAt 来定义临时变量,然后引用它来获取text 字段:

      db.collection.aggregate([
          {
              $addFields: {
                  text1: {
                      $let: {
                          vars: {
                              first: {
                                  $arrayElemAt: [ "$arr", 0 ]
                              }
                          },
                          in: "$$first.text"
                      }
                  }
              }
          }
      ])
      

      【讨论】:

      • 如何通过项目/对象上的特定键添加所有项目,而不仅仅是第一个?
      猜你喜欢
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 2022-11-23
      相关资源
      最近更新 更多