Dino Geek, try to help you

How to establish a reference relationship in MongoDB?


MongoDB is a NoSQL database which works on document oriented storage. It doesn’t support traditional SQL joins but uses a concept known as referencing and embedded documents instead.

Here’s an example of how to establish a reference relationship:

1. Create two collections, one called “authors” and the other “books”.

1. When you add data to “authors”, MongoDB will automatically assign a unique “\_id” for each author.

```
db.authors.insert({ name: ‘George R. R. Martin’, age: 71
})
```

1. Then when you add data to “books”, you can include the authors’ “\_id” as a reference.

```
db.books.insert({ title: ‘A Game of Thrones’, author_id: ObjectId(“…”)
})
```

1. You can then use this reference to lookup related data using `$lookup` operator provided by MongoDB.

```
db.books.aggregate([{ $lookup: { from: ‘authors’, localField: ‘author_id’, foreignField: ‘_id’, as: ‘author‘ }
}])
```

This technique is called “manual references”. However, if you had a one-to-one or one-to-few relationship you might consider using an “embedded document” where you could put all the data relating to one “book” (including the author) into a single document in MongoDB.


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