Pymongo is a Python library used to manipulate MongoDB. MongoDB is a database based on distributed file storage, and its file storage format is similar to JSON, called BSON.

Connecting to a Database

The first step in using PyMonGo is to create a MongoClient to run the mongodb instance

from pymongo import MongoClient
Client = MongoClient()
Copy the code

Getting the database

A single MongoDB instance can support multiple independent databases. With PyMongo, you can use properties on the MongoClient instance to access the database, as well as dictionaries.

db = client.test_database
db = client['test-database']
Copy the code

Access to the Collection

A collection is a set of documents stored in MongoDB that can be considered roughly equivalent to a table in a relational database. Getting a collection in PyMongo works the same way as getting a database:

collection = db.test_collection
collection = db['test-collection']
Copy the code

The Collection in MongoDB is created lazily and the above command does nothing on the MongoDB server. Collection and data are created when the first Document is inserted.

documents

MongoDB uses JSON-style documents to represent (and store) data. In PyMongo, we use dictionaries to represent documents:

post = {
    "author": "Mike"."text": "My first blog post!"."tags": ["mongodb"."python"."pymongo"]."date": datetime.datetime.utcnow()
}
Copy the code

Inserted into the document

Use the insert_one() method to insert a document in the Collection

>>> db.test.count({'x': 1})
0
>>> result = db.test.insert_one({'x': 1})
>>> result.inserted_id
ObjectId('54f112defba522406c9cc208')
>>> db.test.find_one({'x': 1{})u'x': 1.u'_id': ObjectId('54f112defba522406c9cc208')}
Copy the code

Use the insert_many() method to insert multiple documents in the Collection

>>> db.test.count()
0
>>> result = db.test.insert_many([{'x': i} for i in range(2)])
>>> result.inserted_ids
[ObjectId('54f113fffba522406c9cc20e'), ObjectId('54f113fffba522406c9cc20f')]
>>> db.test.count()
2
Copy the code

Update the document

Replace a document in the Collection with the replace_one() method

>>> for doc in db.test.find({}):
.    print(doc)
...
{u'x': 1.u'_id': ObjectId('54f4c5befba5220aa4d6dee7')}
>>> result = db.test.replace_one({'x': 1}, {'y': 1})
>>> result.matched_count
1
>>> result.modified_count
1
>>> for doc in db.test.find({}):
.    print(doc)
...
{u'y': 1.u'_id': ObjectId('54f4c5befba5220aa4d6dee7')}
Copy the code

If the matching document does not exist, you can insert a new document using the upsert option:

>>> result = db.test.replace_one({'x': 1}, {'x': 1}, True)
>>> result.matched_count
0
>>> result.modified_count
0
>>> result.upserted_id
ObjectId('54f11e5c8891e756a6e1abd4')
>>> db.test.find_one({'x': 1{})u'x': 1.u'_id': ObjectId('54f11e5c8891e756a6e1abd4')}
Copy the code

Update a document in the Collection using the update_one() method

>>> for doc in db.test.find():
.    print(doc)
...
{u'x': 1.u'_id': 0}
{u'x': 1.u'_id': 1}
{u'x': 1.u'_id': 2}
>>> result = db.test.update_one({'x': 1}, {'$inc': {'x': 3}})
>>> result.matched_count
1
>>> result.modified_count
1
>>> for doc in db.test.find():
.    print(doc)
...
{u'x': 4.u'_id': 0}
{u'x': 1.u'_id': 1}
{u'x': 1.u'_id': 2}
Copy the code

Update multiple documents in the Collection using the update_many() method

>>> for doc in db.test.find():
.    print(doc)
...
{u'x': 1.u'_id': 0}
{u'x': 1.u'_id': 1}
{u'x': 1.u'_id': 2}
>>> result = db.test.update_many({'x': 1}, {'$inc': {'x': 3}})
>>> result.matched_count
3
>>> result.modified_count
3
>>> for doc in db.test.find():
.    print(doc)
...
{u'x': 4.u'_id': 0}
{u'x': 4.u'_id': 1}
{u'x': 4.u'_id': 2}
Copy the code

Delete the document

Delete a document in the Collection using the delete_one() method

>>> db.test.count({'x': 1})
3
>>> result = db.test.delete_one({'x': 1})
>>> result.deleted_count
1
>>> db.test.count({'x': 1})
2
Copy the code

Use the delete_many() method to delete multiple documents in the Collection

>>> db.test.count({'x': 1})
3
>>> result = db.test.delete_many({'x': 1})
>>> result.deleted_count
3
>>> db.test.count({'x': 1})
0
Copy the code

Query the document

find()

db.test.find({"hello": "world"})
Copy the code

Only documents with the keyword “hello” with the value “world” are matched. If any of the parameters are of incorrect type, TypeError is raised. Returns the Cursor instance corresponding to this query.

find_one()

Querying a single document

Find_one_and_delete () queries a single document and deletes it, returning the document.

>>> db.test.count({'x': 1})
2
>>> db.test.find_one_and_delete({'x': 1{})u'x': 1.u'_id': ObjectId('54f4e12bfba5220aa4d6dee8')}
>>> db.test.count({'x': 1})
1
Copy the code

If there are multiple query results, you can use sort to delete the first one

>>> for doc in db.test.find({'x': 1}) :.    print(doc)
...
{u'x': 1.u'_id': 0}
{u'x': 1.u'_id': 1}
{u'x': 1.u'_id': 2}
>>> db.test.find_one_and_delete(
.    {'x': 1}, sort=[('_id', pymongo.DESCENDING)])
{u'x': 1.u'_id': 2}
Copy the code

find_one_and_replace()

Query individual documents and replace. The find_one_and_replace() method differs from the find_one_and_update() method in that it replaces only the document that the filter matches, rather than modifying existing documents.

>>> for doc in db.test.find({}):
.    print(doc)
...
{u'x': 1.u'_id': 0}
{u'x': 1.u'_id': 1}
{u'x': 1.u'_id': 2}
>>> db.test.find_one_and_replace({'x': 1}, {'y': 1{})u'x': 1.u'_id': 0}
>>> for doc in db.test.find({}):
.    print(doc)
...
{u'y': 1.u'_id': 0}
{u'x': 1.u'_id': 1}
{u'x': 1.u'_id': 2}
Copy the code

find_one_and_update()

Find a single document and update it, returning the original document or the updated document.

>>> db.test.find_one_and_update(
.   {'_id': 665}, {'$inc': {'count': 1}, '$set': {'done': True{}})u'_id': 665.u'done': False.u'count': 25}}
Copy the code

By default, find_one_and_update() returns the document before the update. To return the updated document, set the return_docuemnt parameter.

>>> from pymongo import ReturnDocument
>>> db.example.find_one_and_update(
.    {'_id': 'userid'},
.    {'$inc': {'seq': 1}},
.    return_document=ReturnDocument.AFTER)
{u'_id': u'userid'.u'seq': 1}
Copy the code

You can limit the fields returned

>>> db.example.find_one_and_update(
.    {'_id': 'userid'},
.    {'$inc': {'seq': 1}},
.    projection={'seq': True.'_id': False},
.    return_document=ReturnDocument.AFTER)
{u'seq': 2}
Copy the code

If the document does not exist, you can use the upsert parameter to create the document

>>> db.example.delete_many({}).deleted_count
1
>>> db.example.find_one_and_update(
.    {'_id': 'userid'},
.    {'$inc': {'seq': 1}},
.    projection={'seq': True.'_id': False},
.    upsert=True..    return_document=ReturnDocument.AFTER)
{u'seq': 1}
Copy the code

If there are multiple query results, you can use sort to update the first one after sort

>>> for doc in db.test.find({'done': True}) :.    print(doc)
...
{u'_id': 665.u'done': True.u'result': {u'count': 26}}
{u'_id': 701.u'done': True.u'result': {u'count': 17}}
>>> db.test.find_one_and_update(
.    {'done': True},
.    {'$set': {'final': True}},
.    sort=[('_id', pymongo.DESCENDING)])
{u'_id': 701.u'done': True.u'result': {u'count': 17}}
Copy the code

statistical

count()

Gets the number of documents in the collection.

The last

For more information about the PyMongo API, please visit the official documentation