【发布时间】:2014-08-29 15:20:23
【问题描述】:
我正在尝试创建观看次数最多的元素(作者)的聚合。
这是我收集的用户:
{
"_id" : ObjectId("54008ac8145a6cc5058b456b"),
"history" : {
"authors" : [
{
"name" : "michou",
"count" : {
"all" : NumberLong(1),
"2014" : NumberLong(1),
"201408" : NumberLong(1),
"2014w35" : NumberLong(1)
}
}
]
}
}
{
"_id" : ObjectId("54008ac8145a6ccb058b4570"),
"history" : {
"authors" : [
{
"name" : "petitBonhommeEnMousse",
"count" : {
"all" : NumberLong(2),
"2014" : NumberLong(2),
"201408" : NumberLong(2),
"2014w35" : NumberLong(2)
}
},
{
"name" : "lordVador",
"count" : {
"all" : NumberLong(1),
"2014" : NumberLong(1),
"201408" : NumberLong(1),
"2014w35" : NumberLong(1)
}
}
]
}
}
{
"_id" : ObjectId("54008ac8145a6ccf058b456c"),
"history" : {
"authors" : [
{
"name" : "lordVador",
"count" : {
"all" : NumberLong(1),
"2014" : NumberLong(1),
"201408" : NumberLong(1),
"2014w35" : NumberLong(1)
}
}
]
}
}
我想获得的是用户在过去三周内看到作者的次数列表。
为此,当用户看到一个页面时,我会增加键“2014w35”、“2014w36”的值...(一年中的星期数)。
这是第一次尝试:
db.users.aggregate(
[
{ $match: { history_updated: "20140829" } },
{ $unwind: "$history.authors" },
{ $group :
{
"_id" : "$history.authors.name",
"total2014w35" : {"$sum" : "$history.authors.count.2014w35"},
"total2014w34" : {"$sum" : "$history.authors.count.2014w34"},
"total2014w33" : {"$sum" : "$history.authors.count.2014w33"}
}
},
{ $project: {
"_id" : 1,
"total" : {
$add : [
"$total2014w35",
"$total2014w34",
"$total2014w33"
]
}
}
}
]
)
返回查看作者的列表以及查看次数,但不按用户分隔。这是总数:
{ "_id" : "lordVador", "total" : NumberLong(2) }
{ "_id" : "petitBonhommeEnMousse", "total" : NumberLong(2) }
{ "_id" : "michou", "total" : NumberLong(1) }
我的第二次尝试是按 _id 分组:
db.users.aggregate(
[
{ $match: { history_updated: "20140829" } },
{ $unwind: "$history.authors" },
{
$group :
{
"_id" : "$_id",
....
当然,这会返回用户查看的作者总数。但没有作者详细信息。
{ "_id" : ObjectId("54008ac8145a6ccb058b4570"), "total" : NumberLong(3) }
{ "_id" : ObjectId("54008ac8145a6ccf058b456c"), "total" : NumberLong(1) }
{ "_id" : ObjectId("54008ac8145a6cc5058b456b"), "total" : NumberLong(1) }
我想要的是两者的结合。我想为每个用户(集合中的文档)提供作者列表,每个用户在过去 3 周内看到他/她的次数。
类似:
{ "_id" : ObjectId("54008ac8145a6ccb058b4570"), [{ "lordVador" : NumberLong(3) },{ "michou" : NumberLong(1) } ] }
{ "_id" : ObjectId("54008ac8145a6ccf058b456c"), [{ "petitBonhommeEnMousse" : NumberLong(1) } ] }
{ "_id" : ObjectId("54008ac8145a6cc5058b456b"), [{ "lordVador" : NumberLong(1) } ] }
你们中有人知道如何混合它们吗?
【问题讨论】:
-
我不明白你在追求什么。请解释得更清楚。什么是用户?您作为示例提供的每个文档都代表一个用户?在这种情况下,您想要的信息似乎几乎就在原始文档中。像“2014w35”这样的奇怪键是什么?你为什么(显然)使用值作为键?你为什么不使用日期?
-
嗨,如果不清楚,抱歉。我更新了我的问题。是的,集合中的每个文档都是一个用户。我想为每个用户(集合中的文档)提供作者列表,其中每个用户在过去 3 周内看到他/她的次数。 2014w35 代表 2014 年的第 35 周。我没有使用日期,因为我按周存储它。
标签: mongodb aggregation-framework mongodb-php