Skip to content

Instantly share code, notes, and snippets.

@pdesterlich
Created December 2, 2015 08:53
Show Gist options
  • Save pdesterlich/ede802d2cd823ef8aa6b to your computer and use it in GitHub Desktop.
Save pdesterlich/ede802d2cd823ef8aa6b to your computer and use it in GitHub Desktop.
mongodb limit array documents
collection: people
{
name: 'some name',
age: 23,
...
groups: [
{
id: 1,
...
},
...
]
}
to find all persons having groups.id = 1 in groups
db.people.find({ 'groups.id': 1 })
to find all persons having groups.id = 1 in groups, returning only matching groups
db.people.find({ 'groups.id': 1 }, { groups: { $elemMatch: { id: 1 }}})
https://docs.mongodb.org/manual/reference/operator/projection/elemMatch/#proj._S_elemMatch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment