svs teja
svs teja

Reputation: 1017

Is is possible perform aggregation on a collection and update the same collection?

{ "_id" : 1, "quizzes" : [ 10, 6, 7 ], "labs" : [ 5, 8 ], "final" : 80, "midterm" : 75 ,"extraMarks":10}
{ "_id" : 2, "quizzes" : [ 9, 10 ], "labs" : [ 8, 8 ], "final" : 95, "midterm" : 80 }
{ "_id" : 3, "quizzes" : [ 4, 5, 5 ], "labs" : [ 6, 5 ], "final" : 78, "midterm" : 70 }

These are the documents in my collection. Using the pipeline query as suggested in

$add with some fields as Null returning sum value as Null

I am able to project the sum of fields using this query:

db.students.aggregate([
  {
    "$project": {
      "final": 1,
      "midterm": 1,
      "examTotal": {
        "$add": [
          "$final",
          "$midterm",
          {
            "$ifNull": [
              "$extraMarks",
              0
            ]
          }
        ]
      }
    }
  }
])

Now we have to update the students collection a new field called total as field similar to exam total in the above projection?

Upvotes: 0

Views: 87

Answers (1)

ray
ray

Reputation: 15256

Starting from MongoDB 4.2, you can update with aggregation pipeline.

db.students.update({},
[
  {
    $set: {
      "total": {
        "$add": [
          "$final",
          "$midterm",
          {
            "$ifNull": [
              "$extraMarks",
              0
            ]
          }
        ]
      }
    }
  }
])

Here is the Mongo playground for your reference.

Upvotes: 0

Related Questions