0

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?

3
  • use $multiply operator docs.mongodb.com/manual/reference/operator/aggregation/multiply Commented Nov 1, 2019 at 7:27
  • @sushantmehta can you provide an example? I am unable to set total count as a variable at first place .. Commented Nov 1, 2019 at 7:30
  • You cannot use variables for the aggregation $limit stage; it has to be an integer literal (e.g., 5 ). Commented Nov 1, 2019 at 8:35

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.