I have requirement to update the data based on the inputs using recordID
, each recordID
has count
of associated records. since associated records has huge volume of data , I wanted to control the number of update based on the associated records count via configuration. So in the query, i want to sum the associated document count and should not cross limit configured in property. I wanted to fetch the records using $sum (aggregation) operation in the aggregate query but not sure how to add the criteria.
{
"_id" : ObjectId("5f8f52168"),
"recordID" : "11989",
"count" : NumberInt(5)
}
{
"_id" : ObjectId("5f8f52148"),
"recordID" : "2561",
"count" : NumberInt(10)
}
{
"_id" : ObjectId("5f8f52038"),
"recordID" : "57546",
"count" : NumberInt(30)
}
{
"_id" : ObjectId("5f8f52138"),
"recordID" : "12623",
"count" : NumberInt(40)
}
{
"_id" : ObjectId("5f8f52188"),
"recordID" : "199429",
"count" : NumberInt(50)
}
{
"_id" : ObjectId("5f8f52148a"),
"recordID" : "12793",
"count" : NumberInt(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" : NumberInt(5)
}
{
"_id" : ObjectId("5f8f52148"),
"recordID" : "2561",
"count" : NumberInt(10)
}
{
"_id" : ObjectId("5f8f52038"),
"recordID" : "57546",
"count" : NumberInt(30)
}
Example2 : when totalSum<=70, query should return below documents.
count <=70 ( count : 30 + 35 = 65 )
{
"_id" : ObjectId("5f8f52038"),
"recordID" : "57546",
"count" : NumberInt(30)
}
{
"_id" : ObjectId("5f8f52138"),
"recordID" : "12623",
"count" : NumberInt(35)
}
Mongo query some thing
db.records.aggregate({ $match: {} },
{ $group: { _id : null, sum : { $sum: "$count" }
--where sum<=50
} });