I have a MongoDB collection where I have an array of objects and I want to add an incremental index value to each element of the array of objects.
Like index starts from 0 to array length – 1.
db.collection.aggregate([
{
"$unwind": "$array"
},
{
"$addFields": {
"array.index": {
"$add": [
{
"$ifNull": ["$index", 0]
},
1
]
}
}
},
{
"$group": {
"_id": "$_id",
"array": {
"$push": "$$ROOT.array"
}
}
}
])
2
Answers
MongoDB playground link:
https://mongoplayground.net/p/SWw7rIYHNcj$unwind stage:
Opens an array field ($array) from the input documents.
Creates a new document for each element in the array.
Includes the array index of each element in a new field using includeArrayIndex.
$addFields stage:
Adds a new field ("array.index") to each document.
Converts the "index" field to an integer using the $toInt operator..
$group stage:
Groups documents based on the "_id" field.
Creates an "array" field within each group using the $push operator.
Here’s another way to do it. Comments are in the pipeline.
Try it on mongoplayground.net.