Last active
September 10, 2016 02:43
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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" | |
} | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
This aggregate functions performs following steps to produce the filtered array:
So what's going on?
To have better understanding, you can remove the pipe process (Step 2-4) and incrementally adding it to the aggregate during your understanding process.
Step 1 - is a filter to document in the collection. The result is all documents where any of zip is "11111". Using sample data, it returns 2 document.
Step 2 - unwind process will extract each individual addresses into different documents. Using sample data, it returns 4 documents. Each document contains single address.
Step 3 - is a filter to document in the in-memory document. These documents now only has single address each - therefore re-applying same filter as Step 1, will remove un-match address from the result.
Step 4 - is a grouping process. In-memory document contains filtered document, with single addresses each - it is also filtered after Step 3 was applied. Grouping will construct original presentation of the document - with filtered array of addresses.