# 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)
```
