在 mongodb 聚合的阶段后输出具有序列数字 ID 的新集合

Out new collection with sequence numeric id after stages in mongodb aggregate

在 MongoDB 聚合管道的某些阶段之后,我正在尝试输出一个集合。 out 集合需要包含一个带有序列数字 ID(1、2、3、4 等...)的 ID。

db.getCollection('MY_COLLECTION').aggregate([{
    $addFields: {
      "dataEntries.targetCol1": "$dataEntries.col1",
      "dataEntries.targetCol2": "$dataEntries.col2"
    }
  },
  {
    $project: {
      "_id": 0,
      "dataEntries.col1": 0,
      "dataEntries.col2": 0,
      "dataEntries.col3": 0,
      "dataEntries.col4": 0
    }
  },
  {
    $unionWith: {
      coll: "MY_COLLECTION",
      pipeline: [{
          $addFields: {
            "dataEntries.targetCol1": "$dataEntries.col3",
            "dataEntries.targetCol2": "$dataEntries.col4"
          }
        },
        {
          $project: {
            "_id": 0,
            "dataEntries.col1": 0,
            "dataEntries.col2": 0,
            "dataEntries.col3": 0,
            "dataEntries.col4": 0
          }
        }
      ]
    }
  },
  {
    $out: "test_out"
  }
])

结果集合包含一个 objectId 作为 id。

/* 1 */
{
    "_id" : ObjectId("6239cb749482cf6b13248a80"),
    "dataEntries" : {
        "targetCol1" : "101-A",
        "targetCol2" : "101"
    }
}

/* 2 */
{
    "_id" : ObjectId("6239cb749482cf6b13248a81"),
    "dataEntries" : {
        "targetCol1" : "101-B",
        "targetCol2" : "101"
    }
}

有没有办法为每个文档设置 id 序列数字计数器? 预期结果:

/* 1 */
{
    "_id" : 1,
    "dataEntries" : {
        "targetCol1" : "101-A",
        "targetCol2" : "101"
    }
}

/* 2 */
{
    "_id" : 2,
    "dataEntries" : {
        "targetCol1" : "101-B",
        "targetCol2" : "101"
    }
}

在MongoDB5.0中很简单:

db.collection.aggregate([
   {
      $setWindowFields: {
         sortBy: { _id: 1, },
         output: { _id: { $documentNumber: {} } }
      }
   }
])

在早期版本中,需要做的事情有点多:

db.collection.aggregate([
   {
      $group: {
         _id: null, data: { $push: "$$ROOT" }
      }
   },
   {
      $set: {
         data: {
            $map: {
               input: "$data",
               in: {
                  $mergeObjects: ["$$this",
                     { _id: {$add: [{ $indexOfArray: ["$data._id", "$$this._id"] }, 1]} }
                  ]
               }
            }
         }
      }
   },
   { $unwind: "$data" },
   { $replaceWith: "$data" }
])