Created
March 29, 2021 21:31
-
-
Save Xetera/db14670e090798ab0bad68a18bb5aade to your computer and use it in GitHub Desktop.
Return a nested subdocument inside an array field from a mongodb query
This file contains hidden or 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
// Aggregates are a powerful mongodb tool that allows us to craft complex queries. | |
// In this case it helps prevent repetition in a situation where we would have to | |
// query a document with a filter, then use a duplicate `Array.find` logic to | |
// extract the subdocument we were already expecting to find in the first place. | |
// Example person document | |
{ | |
name: "jason", | |
pets: [{ | |
type: "dog", | |
name: "nasus" | |
}, { | |
type: "bat", | |
name: "donga dunderson" | |
}] | |
} | |
const jasonsDog = await people.aggregate([ | |
// unwind the pets array so each pet represents a separate document | |
// in the pipeline. This results in breaking our documents up like: | |
// { name: "jason", pets: { type: "dog", name: "nasus" } } | |
// { name: "jason", pets: { type: "bat", name: "donga dunderson" } } | |
{ "$unwind": "pets" }, | |
// filter the resulting collection | |
{ "$match": { name: "jason", "pets.type": "dog" } }, | |
// replace the root with pets, equivalent to accessing `result.pets` in code | |
{ "$replaceRoot": { newRoot: "pets" } | |
}]) | |
console.log(jasonsDog) // { type: "dog", name: "nasus" } | |
// Note: aggregate pipelines are not available on mongodb atlas free tier |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment