Home > Net >  Calculated fields in the same $project stage of the pipeline aggregate mongodb?
Calculated fields in the same $project stage of the pipeline aggregate mongodb?

Time:10-23

I am new working with mongodb. I am trying to use calculated fields in the $project stage, to resolve other fields.

I show you a simplified example.

input

    [
  {
    a: 5,
    b: 3
  },
  {
    a: 2,
    b: 1
  },
  
]

Code

db.collection.aggregate([
  {
    $project: {
      _id: 0,
      c: {
        "$add": [
          "$a",
          "$b"
        ]
      },
      d: {
        "$multiply": [
          "$a",
          "$c"
        ]
      }
    }
  }
])

Output

[
  {
    "c": 8,
    "d": null
  },
  {
    "c": 3,
    "d": null
  }
]

result

I only get null values, I have tried to solve it using $let without results. A simple way to solve it would be to replicate the $add operation, but if it is a complex calculation like the one I am dealing with in my real project and it is replicated many times, as is the case, it could be performing unnecessary operations.

Help to me please

sample playgrond

CodePudding user response:

db.collection.aggregate([
{
"$project": {
  "test": {
    "$let": {
      "vars": {
        "sum": {
          $add: [
            "$a",
            "$b"
          ]
        },
        "d": 3
      },
      "in": {
        "c": "$$sum",
        "d": {
          "$multiply": [
            "$$sum",
            "$b"
          ]
        }
      }
     }
    }
   }
  }
])

Explained:

Set the sum via $let and use it later as variable to calculate the multiplication.

Playground

  • Related