$group 按 MongoDb 聚合中的每个唯一字符串

Posted

技术标签:

【中文标题】$group 按 MongoDb 聚合中的每个唯一字符串【英文标题】:$group by each unique string in MongoDb aggreagte 【发布时间】:2020-06-13 23:21:33 【问题描述】:

我在 MongoDB 中有大量事件文档,我想按 createdAt 进行分组,并为同一天创建的事件计算每个唯一的 title

事件文档是这样的:


   "createdAt": 2020-02-03T00:00:00.000Z,
   "title": "Book meeting"

到目前为止,我得到了输出:

[
        "titles": [
          "Book meeting",
          "Book meeting",
          "Personal meeting",
          "Personal meeting",
          "Book meeting",
          "Book meeting",
          "Book meeting",
          "Book meeting",
          "Training",
          "Book meeting",
          "Book meeting",
          "Book meeting",
          "Book meeting",
          "Book meeting",
          "Book meeting",
          "Book meeting",
          "Digital meeting",
          "Support"
        ],
        "date": "2020-02-03T00:00:00.000Z"
, ...events ],

但我希望它是:


        "Book meeting": 10,
        "Digital meeting": 7,
        ...for all titles
        "date": "2020-02-03T00:00:00.000Z"
,

这是我目前正在做的事情:

    Events.aggregate().group(
        _id: 
          createdAt: "$createdAt",
          title: "$title"
        
      )
      .group(
        _id: 
          year:  $year: "$_id.createdAt" ,
          month:  $month: "$_id.createdAt" ,
          day:  $dayOfMonth: "$_id.createdAt" 
        ,
        titles:  $push: "$_id.title" 
      )
      .project(
        _id: 0,
        date: 
          $dateToString: 
            date: 
              $dateFromParts: 
                year: "$_id.year",
                month: "$_id.month",
                day: "$_id.day"
              
            
          
        ,
        titles: 1,
      )

【问题讨论】:

你可以在问题中添加json格式的示例文档吗? 它由createdAttitle组成。就是这样。 你最好添加到问题中,它会帮助你得到答案。 已将其添加到问题中! 是createdAt字段字符串还是ISODate? 【参考方案1】:

试试这个:

Events.aggregate([
  
    $group: 
      _id: 
        title: "$title",
        date: 
          $dateToString: 
            date: "$createdAt",
            format: "%Y-%m-%d"
          
        
      ,
      count: 
        $sum: 1
      
    
  ,
  
    $group: 
      _id: "$_id.date",
      titles: 
        $push: 
          k: "$_id.title",
          v: "$count"
        
      
    
  ,
  
    $addFields: 
      titles: 
        $mergeObjects: [
          
            "date": 
              $concat: [
                "$_id",
                "T00:00:00.000Z"
              ]
            
          ,
          
            $arrayToObject: "$titles"
          
        ]
      
    
  ,
  
    $replaceWith: "$titles"
  
]).exec();

MongoPlayground

【讨论】:

以上是关于$group 按 MongoDb 聚合中的每个唯一字符串的主要内容,如果未能解决你的问题,请参考以下文章

MongoDB——聚合管道之$group操作

MongoDB——聚合管道之$group操作

是否可以在 MongoDB 聚合期间为每个文档创建唯一 ID?

Mongodb聚合$group阶段耗时较长

将字符串字段转换为 MongoDB 中的编码字符串

MongoDb 聚合在 $group 中使用 $sortByCount