在MongoDB聚合中添加数组元素的字段 [英] Add field of array element in MongoDB aggregation
问题描述
我有一个包含对象数组的文档集合:
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
字段.我已经尝试了
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屋!