Dino Geek, try to help you

How to join two collections in MongoDB?


You can use the `$lookup` aggregation stage to join two collections in MongoDB. This operation allows you to combine two collections into a single collection.

Here is an example:

Let’s assume `orders` collection is as follows:
```
{ “_id”: 1, “product”: “abc”, “quantity”: 10, “customer_id”: 1 }
{ “_id”: 2, “product”: “jkl”, “quantity”: 20, “customer_id”: 2 }
{ “_id”: 3, “product”: “xyz”, “quantity”: 30, “customer_id”: 1 }
```
And `customers` collection is as follows:
```
{ “_id”: 1, “name”: “John Doe” }
{ “_id”: 2, “name”: “Jane Doe” }
```

You can use the `$lookup` stage to join the `orders` collection with the `customers` collection on the `customer_id` field:

```
db.orders.aggregate([ { $lookup: { from: “customers”, localField: “customer_id”, foreignField: “_id”, as: “customer_details“ } }
])
```

The output documents will contain a new array field called `customer_details` that contains the matching documents from the `customers` collection.

Remember that MongoDB isn’t a relational database, so heavy use of `$lookup` can be a sign that your data might be better structured in a different type of database.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use