MongoDB组由子文档计数和年份

时间:2015-04-27 00:19:12

标签: mongodb

以下是我的文档样本,名为products:

{
    "_id" : "B000KIT6LQ",
    "brand" : "unknown",
    "category" : "Electronics",
    "price" : "11.99",
    "title" : "Scosche KA2067B 2005..."
    "reviews" : [
        {
            "date" : ISODate("1969-12-31T23:59:59Z"),
            "score" : 5,
            "user_id" : "AK7M5Y7E9O3L7",
            "sentiment" : 0.5,
            "text" : "Bought this so I ...",
            "user_gender" : "female",
            "voted_total" : 0,
            "voted_helpful" : 0,
            "user_name" : "Alex",
            "summary" : "It is what it is"
        },
        {
            "date" : ISODate("1969-12-31T23:59:59Z"),
            "score" : 5,
            "user_id" : "A26VRLMPEA8IDR",
            "sentiment" : 0.352,
            "text" : "Years ago I worked as an...",
            "user_gender" : "male",
            "voted_total" : 0,
            "voted_helpful" : 0,
            "user_name" : "Jack R. Smith",
            "summary" : "Great Kit"
        },
        {
            "date" : ISODate("1969-12-31T23:59:59Z"),
            "score" : 4,
            "user_id" : "A1TGBDVX3QXCRH",
            "sentiment" : 0.19318181818181818,
            "text" : "This insert works great in my ...",
            "user_gender" : "female",
            "voted_total" : 0,
            "voted_helpful" : 0,
            "user_name" : "J. Reed",
            "summary" : "Fits great in my 2006 Spectra5"
        }
    ]
    }

我有很多类别的文件。我正在尝试创建一个mongo查询,这将导致所有类别的评论数量(子文档)每年。我必须按类别和年份分组,并获得评论数量的计数。 这是我到目前为止的查询:

db.products.aggregate([
    { $unwind : "$reviews" },
    { $group: {
        _id: {category: "$category", date: "$reviews.date.getFullYear()"},
        count: { $sum: 1 }}},
    {$sort:{"count": -1}}
])

由于某种原因,getFullYear()方法对我不起作用。如果我按$reviews.date分组,我会得到结果。 任何关于获得正确查询的指针都表示赞赏。 感谢

1 个答案:

答案 0 :(得分:1)

您无法在汇总管道中使用getFullYear()等JavaScript函数,您需要使用等效的aggregation Date operator,在本例中为$year

db.products.aggregate([
    { $unwind : "$reviews" },
    { $group: {
        _id: {category: "$category", date: {$year: "$reviews.date"}},
        count: { $sum: 1 }}},
    {$sort:{"count": -1}}
])