Skip to content

Instantly share code, notes, and snippets.

@umair-khanzada
Last active December 27, 2017 06:32
Show Gist options
  • Save umair-khanzada/759f60ecc99129aa106c8f509352a1c5 to your computer and use it in GitHub Desktop.
Save umair-khanzada/759f60ecc99129aa106c8f509352a1c5 to your computer and use it in GitHub Desktop.
Mongodb query for getting count of chapters in collection.
db.getCollection('your collection').aggregate([
{
"$project": {
chapters: "$books.chapters", _id: "$_id"
}
},
{
"$unwind": "$chapters"
},
{
"$group": {
_id: null, totalChep: {
"$sum": {
"$size": "$chapters"
}
}
}
}
])
//Data model.
{
_id: 01,
books: [
{
name: 'example 1'
chapters: [{chap: 1}, {chap: 2}, {chap: 3}]
},
{
name: 'example 2'
chapters: [{chap: n}, {chap: n}]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment