i want to get count of each categories. i wrote a query for this purpose but this query returned content document. i want only returned count of each categories content and categories info.
Categories collection:
{
"_id" : ObjectId("5a6b98864f1408137f79e507"),
"orderId" : 1,
"parentId" : ObjectId("5a6b8fbd4f1408137f79e3b3"),
"title_en" : "Foreign Movie",
"contentTypes" : 1,
"isEnabled" : true,
"state" : 0,
"expired" : Timestamp(1516998589, 1),
"created" : Timestamp(1516998589, 2),
"updated" : Timestamp(1516998589, 3)
},
{
"_id" : ObjectId("5a6b98864f1408137f79e508"),
"orderId" : 1,
"parentId" : ObjectId("5a6b8fbd4f1408137f79e3b3"),
"title_en" : "Foreign Series",
"contentTypes" : 1,
"isEnabled" : true,
"state" : 0,
"expired" : Timestamp(1516998589, 1),
"created" : Timestamp(1516998589, 2),
"updated" : Timestamp(1516998589, 3)
}
Contents collection:
{
"_id" : ObjectId("5a6b8b734f1408137f79e2cc"),
"categories" : [
{
"_id" : ObjectId("5a6b98864f1408137f79e507")
}
],
"status" : 0,
"created" : Timestamp(1516997542, 4),
"updated" : Timestamp(1516997542, 5)
}
aggregate query:
db.categories.aggregate([
{$match:{"parentId":{$ne : null}}},
{$lookup:{from:"contents",localField:"_id",foreignField:"categories._id",as:"_content"}},
{ $group:
{
_id:"$_id",
"data":{"$first":"$$ROOT"}
}
}
,{$replaceRoot:{"newRoot":{"$mergeObjects":["$data"]}}},
])
result of above query:
{
"_id" : ObjectId("5a6b98864f1408137f79e507"),
"orderId" : 1,
"parentId" : ObjectId("5a6b8fbd4f1408137f79e3b3"),
"title_en" : "Foreign Movie",
"contentTypes" : 1,
"isEnabled" : true,
"state" : 0,
"expired" : Timestamp(1516998589, 1),
"created" : Timestamp(1516998589, 2),
"updated" : Timestamp(1516998589, 3),
"_content" : [
{
"_id" : ObjectId("5a6b8b734f1408137f79e2cc"),
"categories" : [
{
"_id" : ObjectId("5a6b98864f1408137f79e507")
}
],
"status" : 0,
"created" : Timestamp(1516997542, 4),
"updated" : Timestamp(1516997542, 5)
}
]
},
{
"_id" : ObjectId("5a6b98864f1408137f79e508"),
"orderId" : 1,
"parentId" : ObjectId("5a6b8fbd4f1408137f79e3b3"),
"title_en" : "Foreign Series",
"contentTypes" : 1,
"isEnabled" : true,
"state" : 0,
"expired" : Timestamp(1516998589, 1),
"created" : Timestamp(1516998589, 2),
"updated" : Timestamp(1516998589, 3),
"_content" : [] /*array content is empty*/
}
as you show it, _content
is contains contents
documents that returned by $lookup
, i have not this result because i want only returned categories info with count of contents with same categories id like below query:
purpose result:
{
"_id" : ObjectId("5a6b98864f1408137f79e507"),
"orderId" : 1,
"parentId" : ObjectId("5a6b8fbd4f1408137f79e3b3"),
"title_en" : "Foreign Movie",
"contentTypes" : 1,
"isEnabled" : true,
"state" : 0,
"expired" : Timestamp(1516998589, 1),
"created" : Timestamp(1516998589, 2),
"updated" : Timestamp(1516998589, 3),
"contentCount":1,
"_content" : [
{
"_id" : ObjectId("5a6b8b734f1408137f79e2cc")
}
]
}