# Collections & the _id Field — MongoDB Fundamentals: Documents, Queries and Indexes

Source: https://www.skillbyai.com/en/mongodb/mongo-collections

> Group documents into collections, map them to relational terms and understand the auto-generated _id field.

## Collections vs tables

A **collection** groups related documents, similar to a table. But unlike a table, documents in the same collection don't need identical fields.

## Table → collection, row → document

Roughly: **database** ↔ database, **table** ↔ collection, **row** ↔ document, **column** ↔ field.

## The _id field

Every document gets a unique `_id` — MongoDB auto-generates an `ObjectId` if you don't supply one.

```javascript
db.users.findOne()
```

Output:

```
{
  _id: ObjectId("65f1a2b3c4d5e6f7a8b9c0d1"),
  name: "Ada Lovelace"
}
```

**Quiz:** What happens if you insert a document without an _id?

- [ ] The insert fails
- [ ] _id is left null
- [x] MongoDB auto-generates an ObjectId
- [ ] It stores the document in a trash collection

*Answer:* MongoDB auto-generates an ObjectId. MongoDB always ensures a unique _id, generating an ObjectId when one isn't provided.
