I have a collection of documents containing an array of objects:
db.collection.insert({
arr: [
{ id: 1, text: 'foo' },
{ id: 2, text: 'bar' },
]
});
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' }
}
]);
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.
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"
}
}
}
}
])
One way to extract a field of an array element is to project the first element using $arrayElemAt
in a $project
stage, then to access the desired field, e.g. text
, in a second $project
stage:
db.collection.aggregate([
{
$project: {
elem1: {
$arrayElemAt: ["$arr", 0]
}
}
},
{
$project: {
text1: "$elem1.text"
}
}
])
Mongo Playground.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With