在MongoDB聚合中添加数组元素的字段

编程入门 行业动态 更新时间:2024-10-24 14:27:53
本文介绍了在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 的各种变体"mongoplayground/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,因为它看起来 $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聚合中添加数组元素的字段

本文发布于:2023-11-22 19:37:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618744.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字段   元素   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!