node.js - Counting nested arrays with mongoose -
i'm using mongodb through mongoose in node.js application.
in db have general format:
books:
bookschema = { variousdata, //books contain pages pages: [{type: pageschema}] }
pages:
pageschema = { variousdata, //pages contain frames frames: [frameschema] }
frames:
frameschema = { variousdata }
i want write count query count total number of frames in pages in books.
so if have content in db:
book1 = { data:data, pages: [ {data:data, frames: [frame1,frame2,frame3] }, {data:data, frames: [frame1,frame2,frame3] }, {data:data, frames: [frame1,frame2,frame3] } ] }
and
book2 = { data:data, pages: [ {data:data, frames: [frame1,frame2] }, {data:data, frames: [frame1,frame2] }, {data:data, frames: [frame1,frame2] } ] }
i'm expecting end result of 15 (9 frames in book 1 , 6 frames in book 2)
all attempts ended errors.
i can write loop, feel mongoose have better alternative.
any suggestions?
thanks all!
the efficient way this:
book.aggregate([ { "$project": { "pages": { "$map": { "input": "$pages", "as": "page", "in": { "$size": "$$page.frames" } }} }}, { "$unwind": "$pages" }, { "$group": { "_id": null, "pages": { "$sum": "$pages" } }} ],function(err,results) { })
basically there $map
operator allows traverse elements of "pages" array, take @ each "frames" array , return $size
. content of "pages" array of sizes each "frames", , therefore count.
then need "add" together. $unwind
array , $sum
page counts each frame $group
.
Comments
Post a Comment