MongoDB stores data records as BSON documents. BSON is the binary representation of JSON.
$ python
>>> from pymongo import MongoClient
>>> client = MongoClient()
>>> col = client.mydb.test
Insert a single document insert_one(document)
>>> result = col.insert_one({'x':1})
>>> result.inserted_id
ObjectId('583c16b9dc32d44b6e93cd9b')
Insert multiple documents insert_many(documents)
>>> result = col.insert_many([{'x': 2}, {'x': 3}])
>>> result.inserted_ids
[ObjectId('583c17e7dc32d44b6e93cd9c'), ObjectId('583c17e7dc32d44b6e93cd9d')]
Replace a single document matching the filter replace_one(filter, replacement, upsert=False)
.
(to insert a new document if matching document doesn't exist, use upsert=True
)
>>> result = col.replace_one({'x': 1}, {'y': 1})
>>> result.matched_count
1
>>> result.modified_count
1
Update a single document matching the filter update_one(filter, update, upsert=False)
>>> result = col.update_one({'x': 1}, {'x': 3})
Update one or more documents that match the filter update_many(filter, update, upsert=False)
>>> result = col.update_many({'x': 1}, {'x': 3})
Query the database find(filter=None, projection=None, skip=0, limit=0, no_cursor_timeout=False)
. The filter argument is a prototype document that all results must match.
>>> result = col.find({'x': 1})
Get a single document from the database find_one(filter=None)
>>> result = col.find_one()
query={'x':1}
projection={'_id':0, 'x':1} # show x but not show _id
result=col.find(query,projection)
Delete a single document matching the filter delete_one(filter)
>>> result = col.delete_one({'x': 1})
>>> result.deleted_count
1
Delete one or more documents matching the filter delete_many(filter)
>>> result = col.delete_many({'x': 1})
>>> result.deleted_count
3
PyMongo also provides find_one_and_delete()
, find_one_and_update()
and find_one_and_replace()
functionality.