【发布时间】:2017-08-16 17:16:08
【问题描述】:
我试图获取用户喜欢、分享或评论的内容的总和。
我的内容模型具有以下结构。
Content = {
_id: ObjectId(),
author: ObjectId(),
value: <string of post content>
tags: [<trings>],
likes: [array of user ids],
shares: [array of user ids],
comments: [{
ContentId( of the same schema ),
User Id
}]
}
现在,id 喜欢聚合内容文档, 并得到这样的结果。
{
likes: 20,
shares: 10,
comments: 5
}
所以,简而言之,只要有内容, 其中用户 id 在 likes 数组中, likes 增加 1。
共享和 cmets 也是如此。
我不确定聚合框架是否可以做到这一点。 我认为不是,但也许一些 mongodb 大师更了解
快速编辑。部分基于提交的第一篇文章,我做了这个。 现在,它似乎工作了,但我确定有某种陷阱,我错过了,因为它看起来太简单了:)
db.getCollection('contents').aggregate( [
{$facet: {
"likes": [
{$match: {likes: ObjectId("596537d6b63edc2318ee9f0c")} },
{$group: {
_id : "$likes",
count: { $sum: 1 }
}},
{ $project: { count: 1} }
],
"shares": [
{$match: {shares: ObjectId("596537d6b63edc2318ee9f0c")} },
{$group: {
_id : "$shares",
count: { $sum: 1 }
}},
{ $project: { count: 1} }
],
"posts": [
{$match: {$and: [
{user: ObjectId("596537d6b63edc2318ee9f0c")},
{parent: {$exists: false} }
]} },
{$group: {
_id : "$_id",
count: { $sum: 1 }
}},
{ $project: { count: 1} }
]
}
}]);
你能发现上面的代码有什么问题吗?
【问题讨论】:
标签: mongodb aggregation-framework nosql