# Collections & the _id Field — MongoDB

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

> Collections group documents; _id uniquely identifies each one.

## 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
- [x] MongoDB auto-generates an ObjectId
- [ ] _id is left null

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