> 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/master/crud/read/pymongo.md).

# PyMongo

## Basic Operations

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

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

* Add key/value pairs to restrict the search.

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

* Add more key/value pairs for multiple conditions.

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

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

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

## Operators

### $lt and $lte

```python
db.collection.find({'field' : {'$lt': 2}})
db.collection.find({'field' : {'$lte': 1}}) 
```

### $gt and $gte

```python
db.collection.find({'field' : {'$gt': 1}})
db.collection.find({'field' : {'$gte': 2}}) 
```

### $ne

```python
db.collection.find({'field' : {'$ne' : 'value'}}) 
```

### $in and $nin

```python
db.collection.find({'field' : {'$in' : ['element_1', 'element_2']}})
db.collection.find({'field' : {'$nin' : ['element_1', 'element_2']}})
```

### $or

```python
db.collection.find({"$or":[{'field_1' :'value'}, {'field_2' : 'value'}]}) 
```

### $all

```python
db.collection.find({ <field>: { $all: [ <value1>, <value2>, ... ] } })
```

### $elemMatch

```python
db.collection.find({"<array_field>":{"$elemMatch":{"<field>": "<value>"}}}) 
```

### Query an Embedded Document or Array of Embedded Document

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

### $slice

```python
db.collection.find({}, {"field":{"$slice": <limit>}})
db.collection.find({}, {"field":{"$slice":[<skip>, <limit>]}})
```

## Cursor (?) operator

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

```python
db.store.find().sort( [ ( '_id', -1 ), (‘name’,1) ] )
db.store.find().skip(3)
db.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.count_documents({})
# OR
collection.find().count() # Deprecated
```
