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