Sanjay
Sanjay

Reputation: 1745

MongoDB aggregate with total count as variable

I have a condition which says: Create a mongodb query that pulls 5% of total settled claims by claims examinar and my document for example is: claims collection

{ 
    "_id" : ObjectId("5dbbb6b693f50332a533f4db"), 
    "active" : true, 
    "status" : "settled", 
}

{ 
    "_id" : ObjectId("5dbbb6b693f50332a533f4db"), 
    "active" : true, 
    "status" : "unsettled", 
}

I can calculate the total like this.

db.getCollection("claims").aggregate([
    {$match: { 'status': 'trm'}},
    { $count: "total"}
])

It gives me the count of 42 for example.

So what I am trying to achieve is calculate the total count of settled data, set the total as a variable and apply the 5% of the formula in the $limit section as

{
    $limit: $total * 0.05
}

I am unable to set the total from one pipeline as the variable and apply that in another pipeline.

Help please. How to achieve this type of condition?

Upvotes: 0

Views: 1340

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17858

You can do this by adding project stage and using multiply operator like this:

db.getCollection("claims").aggregate([
  {
    $match: {
      "status": "trm"
    }
  },
  {
    $count: "total"
  },
  {
    $project: {
      "total": {
        $multiply: [
          "$total",
          0.95
        ]
      }
    }
  }
])

https://mongoplayground.net/p/VsypWLI6iJt

Docs: https://docs.mongodb.com/manual/reference/operator/aggregation/multiply

Upvotes: 1

Related Questions