> For the complete documentation index, see [llms.txt](https://lupemaydana.gitbook.io/learn-mongodb/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lupemaydana.gitbook.io/learn-mongodb/the-mongodb-query-language-+-atlas/updating-documents.md).

# Updating Documents

## 📌 updateOne() <a href="#updating-documents-updateone" id="updating-documents-updateone"></a>

updateOne will only update the first one that matches the **filter**

```
db.movieDetails.updateOne({"title": "The Martian"},{$set: {"poster": "new url"}})
```

* First, specify the **filter**.
* Second, specify the “**how**”.

**$set** operator uses a **document** as an argument and uses all the key values from the document to update the document that matches the filter.

## 🤓 Update Operators <a href="#update-operators" id="update-operators"></a>

Official documentation: <https://docs.mongodb.com/manual/reference/operator/update/#id1>​

### For scalar values

* **$set**, Sets the value of a field in a document.
* **$unset**, Removes the specified field from a document.
* **$inc**, increment a value by the specified value to a field

### For array values

* $pop, $pull, $pullAll,
* **$push** creates an array if this does not already exist, **each** is a modifier to use every element as an independent element for the array.

## 📌 updateMany() <a href="#updating-documents-updatemany" id="updating-documents-updatemany"></a>

Will make the same modification to all documents that match the filter.

```
db.movieDetails.updateMany({"rated": null },{$unset: {"rated": ""}})
```

**$unset** operator will remove all the values that match the filter.

## 🤓 Upserts <a href="#upserts" id="upserts"></a>

Update documents that match the filter if there are none insert the update document as a new document in the collection.

```
db.movieDetails.updateOne({ "imdb.id": detail.imdb.id }, 
{ $set: detail }, 
{ Upsert: true });
```

Here you are using a variable called **detail** that has a document’s detail.

The **upsert** word is a keyword, executed when trying to update a document and you do not find it, you insert one instead.

## 📌 replaceOne() <a href="#updating-documents-replaceone" id="updating-documents-replaceone"></a>

```
db.movieDetails.replaceOne(filter, doc);
```

Variables: **filter, doc**

At mongodb shell (**a javascript interpreter** :o) define **filter** variable.

```
let filter = {"title": "House, M,D., Season Four: New Beginnings"}
let doc = db.movieDetails.findOne(filter)
```

The **doc** variable will get one document that matches the filter conditions. Now modify the **doc** variable, to add a genre and a poster field.

*💡 Note: this method will only replace the first document it finds.*
