Skip to content

Instantly share code, notes, and snippets.

@cakriwut
Last active September 10, 2016 02:43
Show Gist options
  • Save cakriwut/50e9dd83e80628ddec961f18e169e16b to your computer and use it in GitHub Desktop.
Save cakriwut/50e9dd83e80628ddec961f18e169e16b to your computer and use it in GitHub Desktop.
How to filter array inside mongoDB document, so it will return a document with filtered array inside.
/* 1 */
{
"_id" : "joe",
"name" : "Joe Bookreader",
"addresses" : [
{
"street" : "123 Fake Street",
"city" : "Faketon",
"state" : "MA",
"zip" : "12345"
},
{
"street" : "1 Some Other Street",
"city" : "Boston",
"state" : "MA",
"zip" : "12345"
}
]
}
/* 2 */
{
"_id" : "driver",
"name" : "Driver X",
"addresses" : [
{
"street" : "123 Fake Street 12222",
"city" : "Faketon",
"state" : "MA",
"zip" : "11111"
},
{
"street" : "1 Some Other Street 34",
"city" : "Boston",
"state" : "MA",
"zip" : "12345"
}
]
}
db.getCollection('sample').aggregate(
{
"$match": {
"addresses.zip" : "11111"
}
},
{
"$unwind" :"$addresses"
},
{
"$match": {
"addresses.zip" : "11111"
}
},
{
"$group" : {
"_id": "$_id",
"addresses" :{
"$addToSet" : "$addresses"
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment