> For the complete documentation index, see [llms.txt](https://koonkim.gitbook.io/mongodb/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://koonkim.gitbook.io/mongodb/2.0/crud/syntax.md).

# Syntax

## What is CRUD?

* MongoDB Database에서 데이터를 Manipulating (조작) 하는 방법은 크게 CRUD로 표현할 수 있습니다.
  * **C**reate: 새로운 Document 를 생성하는 일
  * **R**ead: 이미 존재하는 Document 를 찾고 읽는 일
  * **U**pdate: 이미 존재하는 Document 의 정보를 업데이트 하는 일
  * **D**elete: 이미 존재하는 Document 를 제거하는 일
* CRUD는 다양한 곳에서 사용된다.
  * RDBMS, NOSQL, WEB RESORUCE 긁어 올 때 (PUT, GET, POST, DELETE 등) 등..

## Insert

* Insert syntax
  * insertOne: insert a one single document
  * insertMany: insert multiple documents

```python
collection.insertOne(<document>)
collection.insertMany([<docuemtn1>, <document2>, ...])
collection.insert(<document>)
```

## Update

* 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.updateOne( { 'last_name': ‘Kim' }, { '$set': { 'money' : 1000000 } } )
```

* $set, $unset, $inc, $push, $each, $addToSet, $pop, $pull, $slice, etc...
  * See a below link that is a link for the update operators

{% content-ref url="/pages/-LiIReXgNZdC05bhPOdN" %}
[Operator](/mongodb/2.0/crud/operator.md)
{% endcontent-ref %}

## Read

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

```python
collection.find()
collection.findOne()
```

* Add key/value pairs to restrict the search.

```python
collection.find({<field> : <value>})
```

* Add more key/value pairs for multiple conditions.

```python
collection.find({<field1> : <value1>, <field2> : <value2>})
```

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

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

## Delete

* syntax&#x20;
  * deleteOne: remove a document.&#x20;
  * deleteMany: remove documents.

```python
collection.deleteOne(<query>)
collection.deleteMany(<query>)

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

## Cursor

* syntax

```python
store.find().sort( { '_id': -1 , ‘name’:1 }  )
store.find().skip(3)
store.find().limit(2).skip(3)
```

* MongoDB always performs in the order of sort first, skip second, and limit&#x20;
  * Specifies the order in which the query returns matching document.
  * Note that below two queries return the same answer.&#x20;

```python
db.store.find().sort({'_id': -1}).limit(2)
db.store.find().limit(2).sort({'_id', -1})
```

* Count documents in the store collection.

```python
collection.find().count()
```

## Explain()

Explain은 대부분 데이터베이스 시스템에서 지원을 해주는 기능이다. 사용자의 질의문 (query)을 데이터베이스의 optimizer가 query plan을 통해서 실행하는 것을 보여주는 것이다.&#x20;

* Provides information on the query plan for find() method.&#x20;

* In PyMongo, explain() returns a dictionary. Use a key, ‘executionStats’.

* Example

### explain() in MongoShell

```javascript
db.mycollection.find().explain()
```

### explain() in PyMongo

```python
mycollection.find().explain()
mycollection.find().explain()[‘executionStats’]
```
