在列表中聚合以创建具有单独索引的对象

Aggregate within list to create objects with separate index

输入数据:

[
  {
    "links": true,
    "loggedIn": true
  },
  {
    "booking": {
      "id": "3787847847",
      "details": {
        "time": "2021-10-26 11:30:00.000Z",
        "venue": "LHR Airport"
      },
      "results": [
        {
          "name": "ABC",
          "loggedIn": true
        },
        {
          "name": "DEF",
          "loggedIn": false
        }
      ]
    }
  },
  {
    "booking": {
      "id": "000000000",
      "details": {
        "time": "2021-10-29 12:29:00.000Z",
        "venue": "Singapore Changi Airport"
      },
      "results": [
        {
          "name": "XYZ",
          "loggedIn": true
        }
      ]
    }
  }
]

生成的数组只需要包含“预订”或不包含“链接”的对象。如果有两个单独的“结果”,则需要用它们自己的“详细信息”值将它们分开,最好使用索引。

预期输出:

[
  {
    "id": "3787847847",
    "index": 0,
    "details": {
      "time": "2021-10-26 11:30:00.000Z",
      "venue": "LHR Airport"
    },
    "name": "ABC",
    "loggedIn": true
  },
  {
    "id": "3787847847",
    "index": 1,
    "details": {
      "time": "2021-10-26 11:30:00.000Z",
      "venue": "LHR Airport"
    },
    "name": "DEF",
    "loggedIn": false
  },
  {
    "id": "000000000",
    "index": 0,
    "details": {
      "time": "2021-10-29 12:29:00.000Z",
      "venue": "Singapore Changi Airport"
    },
    "name": "XYZ",
    "loggedIn": true
  }
]

这可以吗?我是 Mongo 的新手,所以即使是起点也会非常有帮助!我尝试使用 filter() 进行聚合,但我不确定如何根据内部“结果”数组创建单独的对象。

编辑:$unwind 完成这项工作,但我想要一个唯一值,例如具有相同 ID 的每个对象的索引。

$unwindincludeArrayIndex

db.collection.aggregate([
  {
    "$unwind": {
      path: "$booking.results",
      includeArrayIndex: "arrayIndex"
    }
  }
])

mongoplayground