Find Distinct Values Group By Another Field Mongodb
I have collection with documents like this : { '_id' : ObjectId('5c0685fd6afbd73b80f45338'), 'page_id' : '1234', 'category_list' : [ 'football', 'spo
Solution 1:
you need to write an aggregate pipeline
$match
- filter the documents by criteria$group
- group the documents by key field$addToSet
- aggregate the unique elements$project
- project in the required format$reduce
- reduce the array of array to array by$concatArrays
aggregate query
db.tt.aggregate([
{$match : {"time_broadcast" : "09:13"}},
{$group : {"_id" : "$page_id", "category_list" : {$addToSet : "$category_list"}}},
{$project : {"_id" : 0, "page_id" : "$_id", "category_list" : {$reduce : {input : "$category_list", initialValue : [], in: { $concatArrays : ["$$value", "$$this"] }}}}}
]).pretty()
result
{ "page_id" : "123456", "category_list" : [ "news", "updates" ] }
{
"page_id" : "1234",
"category_list" : [
"sport",
"handball",
"football",
"sport"
]
}
you can add $sort
by page_id
pipeline if required
Post a Comment for "Find Distinct Values Group By Another Field Mongodb"