I have mongo documents
like below, want to perform aggregation to find the errorcodes count for each unique contacts.
{
"_id": {
"$oid": ""
},
"campId": "61baef7817cd8ff66518", //camp1
"contactId": "61aa6fbf77490b0007714273", // contact 1
"title": "Happy Holidays!",
"communicationType": "EMAIL",
"contactedOnTime": {
"$numberLong": "1695182032" // AT TIME1
},
"communicationValidationError": "EMAIL_ADDRESS_NOT_PRESENT"
}
{
"_id": {
"$oid": ""
},
"campId": "61baef7817cd8ff66518", //camp1
"contactId": "61aa6fbf77490b0007714273", // contact1
"title": "Happy Holidays!",
"communicationType": "EMAIL",
"contactedOnTime": {
"$numberLong": "1695182074" // AT TIME2
},
"communicationValidationError": "EMAIL_ADDRESS_NOT_PRESENT"
}
{
"_id": {
"$oid": ""
},
"campId": "61baef7817cd8ff66518", // camp1
"contactId": "61aa6fbf77490b0007714274", // contact2
"title": "Happy Holidays!",
"communicationType": "EMAIL",
"contactedOnTime": {
"$numberLong": "1695182059"
},
"communicationValidationError": "EMAIL_BOUNCED"
}
I have tried below, however this doesn’t eliminate the duplicate contacts for a camp and shows count as 2 instead of 1. I need to pick latest communicationValidationError for unique contacts and get it as totalcounts
of communicationValidationError of a campId.
db.myCollection.aggregate([
{ $project: { _id: 0, campId: 1, contactId: 1, communicationValidationError: 1 } },
{ $sort: { "contactedOnTime.numberLong":-1}},
{ $match: { campId: '61baef7817cd8ff66518' } },
{ $group: { _id: { communicationValidationError: '$communicationValidationError' }, totalErrors: { $sum: 1 } } }
]).pretty()
2
Answers
Though the above answer by @Yong Shun worked, i had to achieve same without using
$setWindowFields:
as i wasn't able to frame it in javaspring-boot
. Here is document showing that the spring supports this operation, however i wasn't able to! Maybe thespring-version
i was using not supporting this.So, i tried to re-write the query using
group
stages. I have put it below for somebody who is facing same issue as mine,Main point:
Thus, the query should be:
$match
$setWindowFields
– Add new fieldrankInLatest
. This will group the documents bycontactId
with the ranking bycontactedOnTime
descending.$match
– Filter the document withrankInLatest: 1
. This will return each document ofcontactId
with the latestcontactedOnTime
.$group
– Group bycommunicationValidationError
and perform the count.Demo @ Mongo Playground