sachin.pandey
sachin.pandey

Reputation: 39

$add,$subtract aggregation-framework in mongodb

Hi i am mentioning the sample data ///collection - test////

{
        "_id" : {
                "date" : ISODate("2020-02-11T17:00:00Z"),
                "userId" : ObjectId("5e43e5cdc11f750864f46820"),
                "adminId" : ObjectId("5e43de778b57693cd46859eb")
        },
        "outstanding" : 212.39999999999998,
        "totalBill" : 342.4,
        "totalPayment" : 130
}
{
        "_id" : {
                "date" : ISODate("2020-02-11T17:00:00Z"),
                "userId" : ObjectId("5e43e73169fe1e3fc07eb7c5"),
                "adminId" : ObjectId("5e43de778b57693cd46859eb")
        },
        "outstanding" : 797.8399999999999,
        "totalBill" : 797.8399999999999,
        "totalPayment" : 0
}

I need to structure a query which does following things-

  1. I need to calculate the actualOutstanding:[(totalBill+outstanding)-totalPayment],

  2. I need to save this actualOutstanding in the same collection & in the same document according to {"_id" : {"date","userId", "adminId" }}

    NOTE: userId is different in both the documents.

Upvotes: 1

Views: 130

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22316

Introduced in Mongo version 4.2+ pipelined updates, meaning we can now use aggregate expressions to update documents.

db.collection.updateOne(
    {
       "adminId" : ObjectId("5e43de778b57693cd46859eb")
       '_id."userId" : ObjectId("5e43e73169fe1e3fc07eb7c5"),
       '_id.date': ISODate("2020-02-11T18:30:00Z"),
    },
    [
        { '$set': { 
              actualOutstanding: {
                  $subtract:[ {$add: ['$totalBill','$outstanding']},'$totalPayment']
             }
        } }
    ]);

For any other Mongo version you have to split it into 2 actions, first query and calculate then update the document with the calculation.

Upvotes: 2

Related Questions