0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

It works like a charm. I really appreciate you. Lastly, I'm just asking because I'm curious, Is it possible to make the same thing with $arrayToObject ?
Hi, I think $arrayToObject is not suitable for this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.