I’m new to making queries in Mongo. I have this single record and I need to find the sections with the same link.
My record:
{
"_id" : ObjectId("1234"),
"name": "singleRecordInMongo",
"__v" : 0,
"sections" : [
{
"name" : "firstElement",
"link" : "https://www.test.com/",
"_id" : ObjectId("624dd0aca5fb565661da1161")
},
{
"name" : "secondElement",
"link" : "https://www.test.com/",
"_id" : ObjectId("624dd0aca5fb565661da1162")
},
{
"name" : "thirdElement",
"link" : "https://www.other.com",
"_id" : ObjectId("624dd0aca5fb565661da1163")
}
]
}
Expected result:
"sections" : [
{
"times" : 2,
"link" : "https://www.test.com/"
}
]
I tried something like this but it didn’t work
db.getCollection('records').aggregate(
{$unwind: "$sections"},
{ $project: {_id: '$_id', value: '$sections'} },
{ $group: {
_id: null,
occurances: {$push: {'value': '$link', count: '$count'}}
}
}
);
2
Answers
Edit:
You can use
$group
:Like this playground returning:
For an aggregate operation that uses JavaScript functions with the
$function
operator, you can use a hash map to keep track of duplicates as follows:Bear in mind
Mongo Playground