I have a collection of documents containing an array of objects:
db.collection.insert({
arr: [
{ id: 1, 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.
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"
}
}
}
}
])