Home > Net >  How to convert deeply nested array with one object to object in mongodb aggregation?
How to convert deeply nested array with one object to object in mongodb aggregation?

Time:02-12

The requirement is to convert all sales array properties to objects with their first elements' quantity value. The collection name is branches and the example data is below.

[
{
    "_id": 111,
    "recs": [
        {
            "date": "01-01-2021",
            "sales": [
                {
                    "quantity": {
                        "P": 14,
                        "K": 0,
                        "U": 0
                    }
                }
            ]
        },
        {
            "date": "02-01-2021",
            "sales": [
                {
                    "quantity": {
                        "P": 23,
                        "K": 0,
                        "U": 0
                    }
                }
            ]
        }
    ]
},
{
    "_id": 21,
    "recs": [
        {
            "date": "01-01-2021",
            "sales": [
                {
                    "quantity": {
                        "P": 11,
                        "K": 0,
                        "U": 0
                    }
                }
            ]
        },
        {
            "date": "02-01-2021",
            "sales": [
                {
                    "quantity": {
                        "P": 31,
                        "K": 0,
                        "U": 0
                    }
                }
            ]
        }
    ]
}]

The expected response is below.

[
{
    "_id": 111,
    "recs": [
        {
            "date": "01-01-2021",
            "sale": {
                "P": 14,
                "K": 0,
                "U": 0
            }
        }
    ]
}]

I tried $map, $addFields but no way I couldn't find a solution.

CodePudding user response:

In $map, you need:

  1. $first to query the first sales.quantity object in recs.sales array.
  2. $mergeObject to merge the current document in recs array with the document from (1).
db.collection.aggregate([
  {
    "$project": {
      _id: 1,
      recs: {
        "$map": {
          "input": "$recs",
          "in": {
            "$mergeObjects": [
              "$$this",
              {
                sales: {
                  $first: "$$this.sales.quantity"
                }
              }
            ]
          }
        }
      }
    }
  }
])

Sample Mongo Playground

  • Related