PyMongo

Basic Operations

  • 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>})
  • Add more key/value pairs for multiple conditions.

db.collections.find({<field1> : <value1>, <field2> : <value2>})
  • Pass a second argument to specify which keys to return/exclude.

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

Operators

$lt and $lte

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

$gt and $gte

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

$ne

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

$in and $nin

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

$or

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

$all

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

$elemMatch

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

Query an Embedded Document or Array of Embedded Document

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

$slice

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

Cursor (?) operator

  • In PyMongo, sort() method must pass parameter as tuple

  • The Syntax of Sort, Skip, Limit are almost same with Mongo Shell

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

    • Specifies the order in which the query returns matching document.

    • Note that below two queries return the same answer.

db.store.find().sort([('_id', -1)]).limit(2)
db.store.find().limit(2).sort([('_id', -1)])
  • Count documents in the store collection.

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

Last updated