# CRUD

Mongo Shell과 같이 CRUD를 지원하기 위해 문법들이 존재한다.

문법은 Syntax Section에서도 언급했듯이 규칙만 알면 그나마 쉽게 암기가 가능하다.

{% content-ref url="broken-reference" %}
[Broken link](https://koonkim.gitbook.io/mongodb/pymongo/syntax/broken-reference)
{% endcontent-ref %}

## Insert

* insert\_one: insert a one single document
* insert\_many: insert multiple documents

```python
collection.insert_one(<document>)
collection.insert_many([<docuemtn1>, <document2>, ...])
collection.insert(<document>)    # Deprecated
```

## Find

* An empty query document (i.e. {}) matches everything in the collection.

```
db.collections.find()
db.collections.find_one()
```

* Add key/value pairs to restrict the search.

```
db.collections.find({<field> : <value>})
```

* Pass a second argument to specify which keys to return/exclude (Projection).

```
db.collections.find({}, {<field1> : 1, <field2> : 1})
db.collections.find({}, {<field1> : 1, <field2> : 0})
# never want to return<field2>
```

## Cursor

* In PyMongo, sort() method must pass parameter as tuple&#x20;
* The Syntax of Sort, Skip, and Limit are almost same as Mongo Shell

Sort Syntax

* In pymongo, sort() method must pass parameter as tuple&#x20;

```
db.store.find().sort( [ ( '_id', -1 ), (‘name’,1) ] ) 
```

* &#x20;Skip, Limit Syntax

```
db.store.find().skip(3)
db.store.find().limit(2).skip(3)
```

{% hint style="danger" %}
MongoDB always performs in the order of **sort** first, **skip** second, and **limit**&#x20;
{% endhint %}

* Note that below two queries return the same answer.&#x20;

```
db.store.find().sort([('_id', -1)]).limit(2)
db.store.find().limit(2).sort([('_id', -1)])
```

* Count documents in the store collection.

```python
collection.count_documents({})
# OR
collection.find().count() # Deprecated
```

### explain

* Provides information on the query plan for find() method.
* In PyMongo, explain() returns a dictionary.&#x20;
  * Use a key, ‘executionStats’.

```
mycollection.find().explain()
mycollection.find().explain()['executionStats']
```

## Update

* 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.

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

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‘

### upsert

* If upsert is True and no documents match the filter, perform an insert.&#x20;

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

## Delete

* delete\_one: remove a document.
* delete\_many: remove documents.

```
collection.delete_one(<query>)
collection.delete_many(<query>)
collection.remove(<query>) # Deprecated
```
