Create and delete

The Python driver provides methods for CRUD just like Ruby and PHP. Following on from Chapter 2Schema Design and Data Modeling, and the books variable that points to our books collection, we can have:

from pymongo import MongoClient
from pprint import pprint

>>> book = {
'isbn': '301',
'name': 'Python and MongoDB',
'price': 60
}
>>> insert_result = books.insert_one(book)
>>> pprint(insert_result)

<pymongo.results.InsertOneResult object at 0x104bf3370>

>>> result = list(books.find())
>>> pprint(result)

[{u'_id': ObjectId('592149c4aabac953a3a1e31e'),
u'isbn': u'101',
u'name': u'Mastering MongoDB',
u'price': 30.0,
u'published': datetime.datetime(2017, 6, 25, 0, 0)},
{u'_id': ObjectId('59214bc1aabac954263b24e0'),
u'isbn': u'102',
u'name': u'MongoDB in 7 years',
u'price': 50.0,
u'published': datetime.datetime(2017, 6, 26, 0, 0)},
{u'_id': ObjectId('593c24443c8ca55b969c4c54'),
u'isbn': u'201',
u'meta': {u'authors': u'alex giamas'},
u'name': u'Mastering MongoDB, 2nd Edition'},
{u'_id': ObjectId('594061a9aabac94b7c858d3d'),
u'isbn': u'301',
u'name': u'Python and MongoDB',
u'price': 60}]

In the previous example, we used insert_one() to insert a single document, which we can define using the Python dictionary notation; we can then query it for all documents in the collection.

The resulting object for insert_one and insert_many has two fields of interest:

  • Acknowledged: A Boolean that is true if the insert has succeeded and false if it hasn't or if write concern is 0 (fire and forget write)
  • inserted_id for insert_one: The ObjectId of the written document and inserted_ids for insert_many: The array of ObjectIds of the written documents

We used the pprint library to pretty-print the find() results. The built-in way to iterate through the result set is by using this:

for document in results:
print(document)

Deleting documents is similar to creating them. We can use delete_one to delete the first instance or delete_many to delete all instances of the matched query.

>>> result = books.delete_many({ "isbn": "101" })
>>> print(result.deleted_count)
1

The deleted_count tells us how many documents were deleted; in our case, it is 1 even though we used the delete_many method.

To delete all documents from a collection, we can pass in the empty document {}.

To drop a collection, we can use drop():

>>> books.delete_many({})
>>> books.drop()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.30.193