我在mongo中有一个项目集合,大致是:
{
_id: ObjectId("...."),
createdAt: ISODate(...),
links: [
{
receipt: {
visits: [ {..} ... ],
id: ...
},
... more links
],
... more project fields
}总结一个links数组,它的子项带有回执,而回执又有一个访问数组。我正在尝试统计每月的“访问量”。我可以按月统计项目,但我想知道是否有mongodb查询专家可以帮助我优雅地计算链接数量。
我想要的输出是所有访问的项目创建时间(即每月)的计数。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 }通过对访问数组的长度求和来测量。
发布于 2019-02-28 14:18:02
请尝试以下查询
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:查找包含createdAt字段的文档
stage2:将链接数组拆分为单独的记录
stage3:按年、月分组,添加总访问量
https://stackoverflow.com/questions/54918204
复制相似问题