Home > OS >  Aggregate within list to create objects with separate index
Aggregate within list to create objects with separate index

Time:10-26

Input data:

[
  {
    "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
        }
      ]
    }
  }
]

The resulting array needs only objects that include "booking" or ones with no "links". If there are two separate "results" they would need to be separated with their own "details" values, preferably with an index.

Expected output:

[
  {
    "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
  }
]

Is this possible to do? I'm new to Mongo so even a starting point would be really helpful! I've tried to aggregate using filter() but I'm not sure on how to create separate objects based on the internal "results" array.

Edit: $unwind does the job, but I want a unique value like an index for each object with the same ID.

CodePudding user response:

$unwind and includeArrayIndex

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

mongoplayground

  • Related