我有一个包含对象数组的文档集合:
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聚合中添加数组元素的字段
发布评论