Created
October 9, 2022 19:15
-
-
Save dcortesnet/a8708e3438c5e71009b25f9aa5eb061b to your computer and use it in GitHub Desktop.
MongoDB lookup 1:N
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
| // Authors Collection | |
| { | |
| "_id" : ObjectId("63430b9e73d381100e27b8e9"), | |
| "name" : "J. K. Rowling", | |
| "books" : [ | |
| ObjectId("63430b8a73d381100e27b8e7"), | |
| ObjectId("63430b8a73d381100e27b8e8") | |
| ] | |
| } | |
| // Books Collection | |
| { | |
| "_id" : ObjectId("63430b8a73d381100e27b8e7"), | |
| "name" : "Philosopher's Stone" | |
| }, | |
| { | |
| "_id" : ObjectId("63430b8a73d381100e27b8e8"), | |
| "name" : "Chamber of Secrets" | |
| } | |
| // Query | |
| db.getCollection("authors").aggregate({ | |
| $lookup: { | |
| from: "books", | |
| localField: "books", | |
| foreignField: "_id", | |
| as: "books" | |
| } | |
| }) | |
| // Result | |
| { | |
| "_id" : ObjectId("63430b9e73d381100e27b8e9"), | |
| "name" : "J. K. Rowling", | |
| "books" : [{ | |
| "_id": ObjectId("63430b8a73d381100e27b8e7"), | |
| "name": "Philosopher's Stone" | |
| }, | |
| { | |
| "_id": ObjectId("63430b8a73d381100e27b8e8"), | |
| "name": "Chamber of Secrets" | |
| } | |
| ] | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment