MongoDB嵌套组?

cla*_*ers 13 mongodb mongodb-query

我正在尝试在mongodb中实现嵌套组查询,并且我试图通过添加外部组而陷入困境.鉴于以下(简化)数据文件:

{
  "timestamp" : ISODate(),
  "category" : "movies",
  "term" : "my movie"
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试获得所有类别的列表,并且在类别中应该有最多的术语.我希望我的输出像这样:

[
 { category: "movies", 
   terms: [ { term: "movie 1", total: 5000 }, { term: "movie 2", total: 200 } ... ]
 },
 { category: "sports", 
   terms: [ { term: "football 1", total: 4000 }, { term: "tennis 2", total: 250 } ... ]
 },
]
Run Code Online (Sandbox Code Playgroud)

我的"内部组"如下所示,并将获得所有类别的前5名:

db.collection.aggregate([
    { $match : { "timestamp": { $gt: ISODate("2014-08-27") } } },
    { $group : { _id :  "$term", total : { $sum : 1 } } },
    { $sort : { total : -1 } },
    { $limit: 5 }
]);

// Outputs:
{ "_id" : "movie 1", "total" : 943 }
{ "_id" : "movie 2", "total" : 752 }
Run Code Online (Sandbox Code Playgroud)

我将如何实施"外部团体"?

另外,有时上面的聚合离子返回一个空值(并非所有文档都有一个术语值).我如何忽略空值?

提前致谢

Phi*_*ipp 26

在这种情况下,您将需要两个组.第一组生成一个文档流,每个术语和类别包含一个文档:

 { $group : { 
      _id :  { 
        category: "$category",
        term: "$term",
      },
      total: { $sum : 1 } 
   }
 }
Run Code Online (Sandbox Code Playgroud)

然后,第二个组将所有具有相同术语的文档合并为一个,使用$ push运算符将类别合并到一个数组中:

 { $group : { 
      _id :  "$_id.category",
      terms: { 
          $push: { 
              term:"$_id.term",
              total:"$total"
          }
      }
   }
 }
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这解决了我的问题,我在两组之间添加了{{$ sort:{total:-1}}},最上面的术语都放在顶部,但是我不知道该如何限制这些术语每个类别说5个。在组之间添加`{$ limit:6}`无效。(我正在尝试对每个类别查询执行前5个字词)。谢谢! (2认同)

Car*_*ero 7

询问:

    db.getCollection('orders').aggregate([
    {$match:{
        tipo: {$regex:"[A-Z]+"}
        }
    },
    {$group:
        { 
            _id:{
                codigo:"1",
                tipo:"$tipo",
            },
            total:{$sum:1}
        }
    },
    {$group:
        {
            _id:"$_id.codigo",
            tipos:
            {
                $push:
                {
                    tipo:"$_id.tipo",
                    total:"$total"
                }
            },
            totalGeneral:{$sum:"$total"}

        }

    }


]);
Run Code Online (Sandbox Code Playgroud)

回复:

{
"_id" : "1",
"tipos" : [ 
    {
        "tipo" : "TIPO_01",
        "total" : 13.0
    }, 
    {
        "tipo" : "TIPO_02",
        "total" : 2479.0
    }, 
    {
        "tipo" : "TIPO_03",
        "total" : 12445.0
    }, 
    {
        "tipo" : "TIPO_04",
        "total" : 12445.0
    }, 
    {
        "tipo" : "TIPO_05",
        "total" : 21.0
    }, 
    {
        "tipo" : "TIPO_06",
        "total" : 21590.0
    }, 
    {
        "tipo" : "TIPO_07",
        "total" : 1065.0
    }, 
    {
        "tipo" : "TIPO_08",
        "total" : 562.0
    }
],
"totalGeneral" : 50620.0
Run Code Online (Sandbox Code Playgroud)

}