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

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

  • Skip, Limit Syntax

  • Note that below two queries return the same answer.

  • Count documents in the store collection.

explain

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

  • In PyMongo, explain() returns a dictionary.

    • Use a key, ‘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.

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.

Delete

  • delete_one: remove a document.

  • delete_many: remove documents.

Last updated

Was this helpful?