Skip to content

Instantly share code, notes, and snippets.

@tangentus
Created February 4, 2021 18:59
Show Gist options
  • Save tangentus/1ea3077739c25d14e0c9a342103f6bd4 to your computer and use it in GitHub Desktop.
Save tangentus/1ea3077739c25d14e0c9a342103f6bd4 to your computer and use it in GitHub Desktop.
Count the number of documents in an embedded array for a collection
SomeCollection.collection.aggregate([
{
"$match": { # This ensures that we only calculate a count where the attribute exists
"some_attribute": {
"$exists" => true
}
}
},
{
"$project": {
count: {
"$size": "$some_attribute"
}
}
}
]).first
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment