[英]Aggregate query on mongo subfields
我在mongo中有一個項目集合,大致是:
{
_id: ObjectId("...."),
createdAt: ISODate(...),
links: [
{
receipt: {
visits: [ {..} ... ],
id: ...
},
... more links
],
... more project fields
}
總結一個links數組,帶有帶有回執的子項,而子項又帶有一個visits數組。 我正在嘗試計算每月的“訪問次數”。 我能夠按月計數項目,但我想知道是否有任何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 }
通過將visits數組的長度相加來度量。
請嘗試以下查詢
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"} }}
}}
])
階段1:查找創建了createdAt
字段的文檔
階段2:將鏈接數組拆分為單個記錄
階段3:按年和月分組並添加總訪問量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.