Home > Blockchain >  Mongodb aggregate addField that contains the current object position in the array query
Mongodb aggregate addField that contains the current object position in the array query

Time:10-02

After the last aggregate pipeline I receive the current array:

[{
    "cdrId": "61574b3e58fb1cae1494df2c",
    "date": "2021-10-01T17:54:06.057Z",
    "intentType": "FALLBACK"
},
{
    "cdrId": "61574b3e58fb1cae1494df2c",
    "date": "2021-10-01T17:54:06.057Z",
    "intentType": "FAQ"
},
{
    "cdrId": "61570b37522aba5e2f205356",
    "date": "2021-10-01T13:20:55.601Z",
    "intentType": "TRANS/DISAM"
},
{
    "cdrId": "61570b37522aba5e2f205356",
    "date": "2021-10-01T13:20:55.601Z",
    "intentType": "FAQ"
}]

I'm looking to add a index field showing the current position of the object in the array. The output is going to be something like this:

[{
    "index": 0,
    "cdrId": "61574b3e58fb1cae1494df2c",
    "date": "2021-10-01T17:54:06.057Z",
    "intentType": "FALLBACK"
},
{
    "index": 1,
    "cdrId": "61574b3e58fb1cae1494df2c",
    "date": "2021-10-01T17:54:06.057Z",
    "intentType": "FAQ"
},
{
    "index": 2,
    "cdrId": "61570b37522aba5e2f205356",
    "date": "2021-10-01T13:20:55.601Z",
    "intentType": "TRANS/DISAM"
},
{
    "index": 3,
    "cdrId": "61570b37522aba5e2f205356",
    "date": "2021-10-01T13:20:55.601Z",
    "intentType": "FAQ"
}]

I will use this value if the next pipe sort this array. So I have it's original position before this sorting.

Is there a way that I can do this with aggregate? I'm using MongoDB 4.2.

CodePudding user response:

Try this one:

db.collection.aggregate([
  // {$sort: {...} },
  {
    $group: {
      _id: null,
      data: { $push: "$$ROOT" }
    }
  },
  {
    $unwind: {
      path: "$data",
      includeArrayIndex: "index"
    }
  },
  {
    $replaceRoot: {
      newRoot: { $mergeObjects: [ "$data", {index: "$index"} ] }
    }
  }
])

Mongo Playground

  • Related