在MongoDB聚合管道中经过一些阶段后,我正在try 推出一个集合.

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.col3": 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"
    }
}

推荐答案

在MongoDB 5.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" }
])

Mongodb相关问答推荐

使用mongosh将大型json文件插入到mongo集合中

如何使用聚合管道查找未销售但存在于产品详细信息集合中的产品的ID

所有文档中嵌套 struct 中的条件匹配-mongodb

根据参考图计算子文档列表的最大值

MongoDb聚合查询问题

MongoDB聚合 - 用另一个数组过滤数组

MongoDB查询仅返回嵌入文档

声明多个模式后无法从数据库中获取数据(mongoose + express + mongodb

Mongo 无法启动

SELECT 字段 AS `anothername` 的 mongodb 等效项

NodeJS中的密码重置

Node + Mongoose:获取最后插入的 ID?

使用 Mongoid 和 Ruby 查询最近 30 天的日期范围?

如果我在 MongoDB 上使用 LINQ,为什么会失go 性能?

如何使用 mgo 和 Go 查询 MongoDB 的日期范围?

Meteor订阅不更新集合的排序顺序

将新值推送到 mongodb 内部数组 - mongodb/php

Mongoose 为所有嵌套对象添加 _id

Spring Data MongoDB - 在哪里以编程方式为 Mongo 集合创建索引?

创建模型时出现mongoose错误