More PyMongo Commands

By Natchuta Wattanapenpaiboon and Purit Punyawiwat

Continuing from our previous article on PyMongo, here we present a relatively more advanced commands that we often use. In addition to CRUD commands, we also mention how to do bulk operations and database backup.

Find If Exists

Sometimes you might want to query for documents which contains a particular field without specifying the field value itself. You can do this using the $exists operator:

ex_col.find( { 'labels.set': {'$exists': true} } )

Update a Field Using the Value of Another Field

If you would like to create a field using value(s) of other field(s), you can use the following code, which creates a new field named ‘initials’ that is composed of the first     letters of first name and surname.

for elem in ex_col.find():
    ex_col.update_one(
        {
           '_id': elem['_id']
        },
        {
           '$set': 
           {
              'initials': elem['first_name'][0] + elem['surname'][0]
           }
        }

Removing a Field

To completely remove the field ‘age’ from the collection, use the $unset operator.

ex_col.update_many( {}, { '$unset': {'age': ''} } )

Bulk

Bulk is a command that will increase the speed of your operations by 10 folds. What bulk does is it allows you to connect to the database only once. With multiple insert, each insert means you would have to connect to the database once. However, with bulk, you would prepare all your data into something like a list and then connect to the database to perform your operations.

There are two types of bulk which you can choose to initialize:

1. Ordered bulk

In an ordered bulk, the operation will be performed according to the order of the element in the list.

bulk = ex_col.initialize_ordered_bulk_op()

2. Unordered bulk

In an unordered bulk, the operation will be performed randomly allowing things to run in parallel which would be faster.

bulk = ex_col.initialize_unordered_bulk_op()

Bulk Insert

Here is an example of how to insert using bulk.

bulk.insert({'test_field': 'test_value'})

Basically, your collection object is bulk.

MongoDump

In order to backup your database, you can use the command mongodump from your terminal.

mongodump -d ex_db -o .

This command would backup all the collection in the database exdb at the directory you created. This would create a folder in your current directory with the same name as your database, in this case, exdb. The folder would contain .bson and .json files for each collection. The link below shows other things you could do with mongodump: https://docs.mongodb.com/manual/reference/program/mongodump/

MongoRestore

Now, with the folder you created from mongodump, you would need a way to restore this backup into your database which is the command mongorestore.

mongorestore --db ex_db_restored ex_db

This command would restore you exdb to the database exdb_restored. If you would like to restore with your old database name, make sure to drop your old database first otherwise this would concatenate the results to your old database and will not replace it. For more information, check out the link below:

https://docs.mongodb.com/manual/reference/program/mongorestore/

Have a question?

Drop us a line and we will get back to you