Sum unique properties in different collection elements in MongoDB and get the resultant Price?

MongoDBDatabaseBig Data Analytics

To calculate the sum of unique properties in different collection elements, use $cond along with $group. This gives the resultant price.

Let us create a collection with documents −

> db.demo580.insertOne(
...    {
...       "Name":"John",
...       "Id1":"110",
...       "Id2":"111",
...       "Price":10.5
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e918cebfd2d90c177b5bcae")
}
>
> db.demo580.insertOne(
... {
...    "Name":"John",
...    "Id1":"111",
...    "Id2":"",
...    "Price":9.5
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e918cecfd2d90c177b5bcaf")
}

Display all documents from a collection with the help of find() method −

> db.demo580.find();

This will produce the following output −

{ "_id" : ObjectId("5e918cebfd2d90c177b5bcae"), "Name" : "John", "Id1" : "110", "Id2" : "111", "Price" : 10.5 }
{ "_id" : ObjectId("5e918cecfd2d90c177b5bcaf"), "Name" : "John", "Id1" : "111", "Id2" : "", "Price" : 9.5 }

Following is the query to sum unique properties in different collection elements −

> db.demo580.aggregate([
...    {
...       $project: {
...          Id1: 1,
...          Id2: 1,
...          Price: 1,
...          match: {
...             $cond: [
...                {$eq: ["$Id2", ""]},
...                "$Id1",
...                "$Id2"
...             ]
...          }
...       }
...    },
...    {
...       $group: {
...          _id: '$match',
...          Price: {$sum: '$Price'},
...          resultId: {
...             $addToSet: {
...             $cond: [
...                {$eq: ['$match', '$Id1']},
...                null,
...                '$Id1'
...             ]
...          }
...       }
...    }
... },
... {$unwind: '$resultId'},
... {$match: {
...       resultId: {
...          $ne: null
...       }
...    }
... },
... {
...    $project: {
...       Id1: '$resultId',
...       Price: 1,
...       _id: 0
...    }
... }
... ])

This will produce the following output −

{ "Price" : 20, "Id1" : "110" }
raja
Published on 15-May-2020 06:15:12
Advertisements