MongoDB and Python


See Port number the default is 27017 (last line in the image above). 
Python has its own library for MongoDB. The name of the available library — “PyMongo”. To import this, run the following command:

from pymongo import MongoClient

  • Create a connection. The very first thing after importing the module — this is to create a MongoClient.

    from pymongo import MongoClient

    client = MongoClient ()

    Then connect to the host and default port. The connection to the host and port is made explicitly. The following command is used to connect MongoClient to a local host that runs on port number 27017.

    client = MongoClient (`host`, port_number)

    example: - client = MongoClient (`localhost`, 27017 )

    This can also be done with the following command:

    client = MongoClient (“mongodb: / / localhost: 27017 / ”)

  • Accessing objects of the database: to create a database or switch to an existing database, we use:
    Method 1: dictionary

    mydatabase = client [`name_of_the_database`]

    Method 2:

    mydatabase = client.name_of_the_database

    If there is no previously created database with this name, MongoDB will implicitly create the database d data for the user. 
    Note. The database fill name will not allow the use of a dash (-) in it. Names like my-Table will throw an error. Thus, underscores are allowed in the name.

  • Accessing the collection: Collections are equivalent to tables in an RDBMS. We access the collection in PyMongo in the same way we access tables in an RDBMS. To access the table, say the name of the database table “myTable”, say “mydatabase”. 
    Method 1:

    mycollection = mydatabase [`myTable`]

    Method 2 :

    mycollection = mydatabase.myTable

    & gt; MongoDB stores the database as dictionaries as shown: & gt;

     record = {title: `MongoDB and Python`, description:` MongoDB is no SQL database`, tags: [`mongodb`,` database `,` NoSQL`], viewers: 104} 

    & # 39; _id & # 39; — this is a special key that is added automatically if the programmer forgets to add explicitly. _id — it is a 12-byte hexadecimal number that ensures that each inserted document is unique. 

  • Insert data inside the collection:
    Methods Used:
     insert_one () or insert_many () 

    We usually use the insert_one () method in our collections. Let`s say we want to enter data named as a record into “myTable” from “mydatabase”.

    rec = myTable.insert_one (record)

    All the code looks like this when you need to implement it.

  • Queries in MongoDB: there are certain fu Query functions that are used to store data in the database. The two most commonly used functions are:
    1. find ()
      find () is used to get more than one document from a query.

  • # importer

    from pymongo import MongoClient

    # create MongoClient

    client = MongoClient ()

    # Connect to port number and host

    client = MongoClient (“mongodb: / / localhost: 27017 / ”)

    # Database access

    mydatabase = client [`name_of_the_database`]

    # Accessing the database collection

    mycollection = mydatabase [`myTable`]

    # dictionary to add to the database

    rec = {

    title: `MongoDB and Python`

    description: `MongoDB is no SQL database`

    tags: [ `mongodb` , ` database` , ` NoSQL` ], 

    viewers: 104  

    # inserting data into the database

    rec = mydatabase.myTable.insert (record)

    for i in mydatabase.myTable.find ({title: `MongoDB and Python` })

      print (i)

    This will output all documents to myTable mydatabase, whose name is — MongoDB and Python.

  • count —  ()
    count () is used to get document numbers with the name passed in parameters.

    print (mydatabase.myTable.count ({title: `MongoDB and Python` }))

    This will output the number of documents in myTable mydatabase, whose name is — MongoDB and Python.

  • These two query functions can be summed up to get the most filtered result, as shown below.

    print (mydatabase.myTable.find ({title: ` MongoDB and Python` }). count ())

  • To print all documents / records inside & # 39; myTable & # 39; databases & # 39; mydatabase & # 39 ;: use the following code:

    from pymongo import MongoClient


    try :

    conn = MongoClient ()

    print ( "Connected successfully !! ! " )


    print ( "Could not connect to Mong oDB " )

    # database name: mydatabase

    db = conn.mydatabase

    # Created or switched to collection names: myTable

    collection = db.myTable

    # Find () all records within the collection name & # 39; myTable & # 39 ;

    cursor = collection.find ( )

    for record in cursor:

    print (record)

  • This article is courtesy of Rishabh Bansal and Shaurya Uppal .

    If you are as Python.Engineering and would like to contribute, you can also write an article via or by posting the article [email protected] See my article appearing on the Python.Engineering homepage and help other geeks.

    Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.