# PyMongo

## Update Operators

* The syntax is identical to update documents between Mongo shell and Pymongo
  * Note that Pymongo uses a dictionary as a document in MongoDB.
  * Warn: Update operators must be written with ' or " , e.g., '$pull‘

```python
 collection.update_one( { 'last_name': ‘Kim' }, { '$set': { 'money' : 1000000 } } )
```

* All operators of MongoDB are available in PyMongo

* $set, $unset, $inc, $push, $each, $addToSet, $pop, $pull, $slice, etc...

* update\_one: Updates a single document within the collection based on the query.&#x20;

* update\_many: Updates multiple documents within the collection based on the query.&#x20;

```python
collection.update_one(<query>, <update>[, <options>])
collection.update_many(<query>, <update>[, <options>])

collection.update(<query>, <update>[, <options>]) # Deprecated
```

## Operators

* Two ways to manipulate values in arrays.
  * By position
  * Position operator (the $ character)
    * When we don’t know what index of the array to modify.
    * Updates only the first match.
  * Example

```python
collection.update_one({<query>}, {"$inc" : {“comments.0.like” : 1}})
collection.update_many({<query>}, {"$inc" : {“comments.$.like” : 1}})
```

* Upsert
  * If upsert is True and no documents match the filter, perform an insert.

```python
collection.update_one(< filter >, < update >, upsert=True)
collection.update_many(< filter >, < update >, upsert=True)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://koonkim.gitbook.io/mongodb/1.1/crud/update/pymongo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
