Skip to content

Instantly share code, notes, and snippets.

@Xetera
Created March 29, 2021 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xetera/db14670e090798ab0bad68a18bb5aade to your computer and use it in GitHub Desktop.
Save Xetera/db14670e090798ab0bad68a18bb5aade to your computer and use it in GitHub Desktop.
Return a nested subdocument inside an array field from a mongodb query
// 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