I have a MongoDB collection where I have an array of objects (low size) 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. Data :
db="abc" : {
"array": [
{
"_id": "a",
"timestamp": "t1",
"type": "object"
}
]
}
db.collection.aggregate([
{
"$unwind": "$array"
},
{
"$addFields": {
"array.index": {
"$add": [
{
"$ifNull": ["$index", 0]
},
1
]
}
}
},
{
"$group": {
"_id": "$_id",
"array": {
"$push": "$$ROOT.array"
}
}
}
])
MongoDB playground link:
https://mongoplayground.net/p/SWw7rIYHNcj
db.collection.aggregate([
{
"$unwind": {
"path": "$array",
"includeArrayIndex": "index"
}
},
{
"$addFields": {
"array.index": {
"$toInt": "$index"
}
}
},
{
"$group": {
"_id": "$_id",
"array": {
"$push": "$$ROOT.array"
}
}
}
])
$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.