需要从nodejs和mongodb
中的集合中获取针对ArticleId的计数/* 1 */
{
"_id" : ObjectId("5836d0f7f8462cbc6d0caffc"),
"DeviceId" : "abcd1234",
"AppType" : "web",
"UserId" : "5836cb01f8462cbc6d0caff8",
"ArticleId" : "5836cb01f8462cbc6d0caff8",
"Timestamp" : ISODate("2016-11-24T11:37:27.851Z")
}
/* 2 */
{
"_id" : ObjectId("5836e5f617632727286475e0"),
"Apptype" : "android",
"DeviceId" : "abcsd1212",
"UserId" : "19283738264817",
"ArticleId" : "5836wp0615555727286475e0",
"Timestamp" : "2016-11-24 12:23:04.484Z"
}
/* 3 */
{
"_id" : ObjectId("583d487803d7691d54a82060"),
"DeviceId" : null,
"AppType" : null,
"UserId" : null,
"ArticleId" : "583d28412f93b67c1500002a",
"Timestamp" : ISODate("2016-11-29T09:20:56.895Z")
}
/* 4 */
{
"_id" : ObjectId("583d4aa564b47b199ca6b71e"),
"DeviceId" : null,
"AppType" : null,
"UserId" : null,
"ArticleId" : "583559814d93b6080d000029",
"Timestamp" : ISODate("2016-11-29T09:30:13.785Z")
}
/* 5 */
{
"_id" : ObjectId("583d4ab364b47b199ca6b71f"),
"DeviceId" : null,
"AppType" : null,
"UserId" : null,
"ArticleId" : "58343672dc1434742700002a",
"Timestamp" : ISODate("2016-11-29T09:30:27.200Z")
}
/* 6 */
{
"_id" : ObjectId("584502efc0e6500558d20874"),
"DeviceId" : null,
"AppType" : null,
"UserId" : null,
"ArticleId" : "583d28412f93b67c1500002a",
"Timestamp" : ISODate("2016-12-05T06:02:23.905Z")
}
where子句就像(ArticleId的集合)
{
"5836d0f7f8462cbc6d0caffc",
"5836e493f2acbd1d34648e78",
"5836dba8a2943528448a3050"
}
需要得到像
这样的结果[{"ArticleId" : "5836d0f7f8462cbc6d0caffc","ViewCount":5},
{"ArticleId" : "5836e493f2acbd1d34648e78","ViewCount":42},
{"ArticleId" : "5836dba8a2943528448a3050","ViewCount":19}]
请提供帮助,如果有任何不清楚的地方,请告诉我,提前谢谢
答案 0 :(得分:1)
使用MongoDB的聚合功能最多可以解决这个问题。
文档可用here
您应该做的是:1)按文章ID汇总(=分组)文件,然后2)计算每组文件的数量。
db.collection_name.aggregate(
[
{
$group : {
_id : { articleId: $ArticleId },
count: { $sum: 1 }
}
}
]
)
(代码未经测试,但仍然是良好的开端)
现在,如果您只需要对某组文章进行计数,您可以事先进行过滤,但这取决于您可能甚至不需要的收藏大小。