简体   繁体   中英

Aggregate query on mongo subfields

I have a projects collection in mongo that is roughly:

{ 

_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. 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.

The output I want is a count of all visits per month of the project creation time (ie. createdAt ), for example:

{ "_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.

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

stage2: Split links array into individual records

stage3: group by year and month and add total visits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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