python mongodb

How Do You Use MongoDB With Python?

If you desire to operate Python and the document-oriented MongoDB database, you have to download the tool from the official website of the project. At the same time, the most current stable version is needed.

In order for the server to function normally, we need a directory, according to the standard settings, /data/db is specified. To specify your own use the key – dbpath.

Next, you need to install the Python library, allowing you to operate MongoDB.

A server can contain several databases at once. In the database, can be placed several assemblies of documents at once. If you compare with the familiar MySQL, then it will be similar to a table. In the collections there are documents. And the document is serialized with data presented in JSON format.

Note that relational databases have a pre-defined data record structure. And in document-oriented databases there’s no rigid structuring, so documents in one collection possess many fields.

When operating PyMongo the creation of MongoClient to run the instance mongod is needed.

So we connect to the standard host and port Or using the MongoDB URI format. One instance of MongoDB can support several independent databases.

In fact, when performing these operations, databases and collections are not physically created. And they are created when you add the first document to this database and this collection.

Data in MongoDB is represented and stored as JSON documents. In PyMongo, we use a document submission document.

Documents can place their own Python types (like datetime.datetime), which are automatically converted to the appropriate BSON types. To add a document to the collection, you can use the insert_one () method. When the document is added, a special key is created – “_id”, if the document doesn’t already contain it.

The value of “_id” must be unique for the collection. insert_one () returns an instance of InsertOneResult. After the first document was added, the post-collection was physically created on the server. The simplest type of query that is executed in MongoDB is find_one (). This method returns one document that matches the query (or none if there were no matches).

This is useful when you know that there is only one suitable document, or are only interested in the first match. As the outcome, we receive a previously added document.

The returned document contains “_id”, which was automatically created when added. find_one () also supports querying for specific elements to which the document should correspond.


Igor Grigorenko

Add comment