How to fetch documents with condition on $sum that it should not cross the limit specified

I need to fetch documents where the total count sum less than or equal to a specified value.

So in the query, I want to sum the documents count and $sum should not cross the limit specified.

A sample format of my MongoDB schema:

[
  {
    "recordID": "11989",
    "count": 5
    
  },
  {
    "recordID": "2561",
    "count": 10
    
  },
  {
    "recordID": "57546",
    "count": 30
    
  },
  {
    "recordID": "12623",
    "count": 40
    
  },
  {
    "recordID": "199429",
    "count": 50
  },
  {
    "recordID": "12793",
    "count": 60
    
  }
]

Example1: Let’s say when totalcount<=50) I need to fetch the documents, in which total count sum less than or equal 50 (totalsum<=50), it should return below documents.

count <=50 ( count = 5 + 10 + 30 )

{ 
    "_id" : ObjectId("5f8f52168"), 
    "recordID" : "11989", 
    "count" : 5
}
{ 
    "_id" : ObjectId("5f8f52148"), 
    "recordID" : "2561", 
    "count" : 10
 }
{ 
    "_id" : ObjectId("5f8f52038"), 
    "recordID" : "57546", 
    "count" : 30
}

Example2 : when totalSum<=20, query should return below documents.

count <=20 ( count : 5 + 10 = 15 )

{ 
    "_id" : ObjectId("5f8f52168"), 
    "recordID" : "11989", 
    "count" : 5
}
{ 
    "_id" : ObjectId("5f8f52148"), 
    "recordID" : "2561", 
    "count" : 10
 }

How to achieve this use case using aggregation framework?

MongoDB Playground

Hi @Tiya_Jose,

Seems like a similar request was made earlier:

Consider reading it and let us know if you have questions

Thanks
Pavel

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.