我在mongodb学习聚合。我在处理收藏品:
{
"body" : ""
,
"email" : "oJJFLCfA@qqlBNdpY.com",
"author" : "Linnie Weigel"
},
{
"body" : ""
,
"email" : "ptHfegMX@WgxhlEeV.com",
"author" : "Dinah Sauve"
},
{
"body" : ""
,
"email" : "kfPmikkG@SBxfJifD.com",
"author" : "Zachary Langlais"
}
{
"body" : ""
,
"email" : "gqEMQEYg@iiBqZCez.com",
"author" : "Jesusa Rickenbacker"
}
]我试着得到每个作者的身体数目。但是,当我执行聚合mongodb的命令和时,结果是1(因为结构只有一个元素)。我怎么才能做这个手术?我和$addToSet试过了。但我不知道如何获得每个元素的集合和操作。
发布于 2014-09-06 07:23:37
为了计算每个作者的注释,您希望由该作者进行$group并对事件进行$sum。基本上只是一个"$sum: 1“操作。但在这里,您似乎将“注释”作为一个数组,它基于您自己的注释和部分数据列表的结束括号。为此,您需要首先使用$unwind进行处理:
db.collection.aggregate([
{ "$unwind": "$comments" },
{ "$group": {
"_id": "$comments.author",
"count": { "$sum": 1 }
}}
])这将获得作者对整个集合的所有作者评论的总数。如果您是在获得每个文档的作者评论总数(或类似于博客帖子模型的内容)之后,那么您可以使用document _id作为组语句的一部分:
db.collection.aggregate([
{ "$unwind": "$comments" },
{ "$group": {
"_id": {
"_id": "$_id"
"author": "$comments.author"
},
"count": { "$sum": 1 }
}}
])然后,如果您希望每个文档只返回一个与数组中的所有作者一起返回的文档,那么从这里开始使用$addToSet,并使用另一个$group管道阶段:
db.collection.aggregate([
{ "$unwind": "$comments" },
{ "$group": {
"_id": {
"_id": "$_id"
"author": "$comments.author"
},
"count": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id._id",
"comments": {
"$addToSet": {
"author": "$_id.author",
"count": "$count"
}
}
}}
])但是,实际上,作者值已经是唯一的,并且“set”没有以任何方式排序,所以您可以在第一次引入一个$push之后使用$sort对列表进行更改,使列表按注释的数量排序:
db.collection.aggregate([
{ "$unwind": "$comments" },
{ "$group": {
"_id": {
"_id": "$_id"
"author": "$comments.author"
},
"count": { "$sum": 1 }
}},
{ "$sort": { "_id._id": 1, "count": -1 } },
{ "$group": {
"_id": "$_id._id",
"comments": {
"$push": {
"author": "$_id.author",
"count": "$count"
}
}
}}
])https://stackoverflow.com/questions/25694290
复制相似问题