CRUD

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

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

Insert

  • insert_one: insert a one single document

  • insert_many: insert multiple documents

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

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

Sort Syntax

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

db.store.find().sort( [ ( '_id', -1 ), (‘name’,1) ] ) 
  • Skip, Limit Syntax

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

  • 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

explain

  • Provides information on the query plan for find() method.

  • In PyMongo, explain() returns a dictionary.

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

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

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

Last updated