在MongoDB聚合中添加数组元素的字段 [英] Add field of array element in MongoDB aggregation

查看:660
本文介绍了在MongoDB聚合中添加数组元素的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a collection of documents containing an array of objects:

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

是否有一种方法可以提取/投影/添加该数组中的一个 one 元素字段?例如,数组第一个元素的text字段.我已经尝试了 $ addFields 的各种变体"https://mongoplayground.net/p/LEBQ1QjppEl" rel ="noreferrer"> MongoPlayground ,

Is there a way to extract/project/add a field of one element in that array? For example, the text field of the first element of the array. I've tried various variations of $addFields in MongoPlayground,

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

,但是什么也没有产生一个text字段.充其量,我得到了上面两种语法,但我只想要一个字段,以便在其上使用$ type,因为它看起来

but nothing produced just one text field. At best, I got both, with the syntax above, but I want only one field, in order to use $type on it, because it appears $type can't inspect array elements.

推荐答案

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

You can use $let with $arrayElemAt to define temporary variable and then reference it to get text field:

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

这篇关于在MongoDB聚合中添加数组元素的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆