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

$ne

$in and $nin

$or

$all

$elemMatch

Query an Embedded Document or Array of Embedded Document

$slice

Cursor (?) operator

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

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

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

  • Count documents in the store collection.

Last updated

Was this helpful?