简体   繁体   English

汇总查询mongo子字段

[英]Aggregate query on mongo subfields

I have a projects collection in mongo that is roughly: 我在mongo中有一个项目集合,大致是:

{ 

_id: ObjectId("...."),
createdAt: ISODate(...),
links: [ 
  { 
    receipt: {
       visits: [ {..} ... ],
       id: ...

  }, 
  ... more links
], 
... more project fields
}

To summarise a links array, with subitems with receipt which in turn has a visits array. 总结一个links数组,带有带有回执的子项,而子项又带有一个visits数组。 I'm trying to count the "visits" per month. 我正在尝试计算每月的“访问次数”。 I am able to count projects by month, but I wondered if any mongodb query gurus could help me do it elegantly for counting up links. 我能够按月计数项目,但我想知道是否有任何mongodb查询专家可以帮助我轻松地完成对链接的计数。

The output I want is a count of all visits per month of the project creation time (ie. createdAt ), for example: 我想要的输出是项目创建时间(即createdAt )每月所有访问的计数,例如:

{ "_id" : "2019-02", "numberofviews" : 73 }
{ "_id" : "2019-01", "numberofviews" : 75 }
{ "_id" : "2018-12", "numberofviews" : 43 }
{ "_id" : "2018-11", "numberofviews" : 83 }
{ "_id" : "2018-10", "numberofviews" : 153 }
{ "_id" : "2018-09", "numberofviews" : 104 }

As measure by summing the lengths of the visits array. 通过将visits数组的长度相加来度量。

Please try the below query 请尝试以下查询

db.projects.aggregate([
    {$match: {"createdAt": {$exists: true}}},
    {$unwind: "$links"},
    {$group : { 
        _id : {$concat: [ {$substr:[{$year : "$createdAt"}, 0, -1]}, "-", {$substr:[{$month : "$createdAt"}, 0, -1]}]},  
        numberofviews : {$sum: { $cond: { if: { $isArray: "$links.receipt.visits" }, then: { $size: "$links.receipt.visits" }, else: "NA"} }}
    }}      
])

stage1: find documents which have createdAt field 阶段1:查找创建了createdAt字段的文档

stage2: Split links array into individual records 阶段2:将链接数组拆分为单个记录

stage3: group by year and month and add total visits 阶段3:按年和月分组并添加总访问量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM