Change language

MongoDB and Python

| |

Required Reasons to choose MongoDB:

  1. It supports a hierarchical data structure (see documentation )
  2. It supports associated arrays such as dictionaries in Python.
  3. Built-in Python drivers for linking a python application to database. Example — PyMongo
  4. It’s designed for big data.
  5. Deploying MongoDB is easy.

MongoDB vs. RDBMS

mongod

or
Method 2:

 net start MongoDB 


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

    " MongoDB stores the database as dictionaries as shown:"

     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 !! ! " )

    except

    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 contribute.python.engineering 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.

    Shop

    Learn programming in R: courses

    $

    Best Python online courses for 2022

    $

    Best laptop for Fortnite

    $

    Best laptop for Excel

    $

    Best laptop for Solidworks

    $

    Best laptop for Roblox

    $

    Best computer for crypto mining

    $

    Best laptop for Sims 4

    $

    Latest questions

    NUMPYNUMPY

    Common xlabel/ylabel for matplotlib subplots

    12 answers

    NUMPYNUMPY

    How to specify multiple return types using type-hints

    12 answers

    NUMPYNUMPY

    Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

    12 answers

    NUMPYNUMPY

    Flake8: Ignore specific warning for entire file

    12 answers

    NUMPYNUMPY

    glob exclude pattern

    12 answers

    NUMPYNUMPY

    How to avoid HTTP error 429 (Too Many Requests) python

    12 answers

    NUMPYNUMPY

    Python CSV error: line contains NULL byte

    12 answers

    NUMPYNUMPY

    csv.Error: iterator should return strings, not bytes

    12 answers

    News


    Wiki

    Python | How to copy data from one Excel sheet to another

    Common xlabel/ylabel for matplotlib subplots

    Check if one list is a subset of another in Python

    sin

    How to specify multiple return types using type-hints

    exp

    Printing words vertically in Python

    exp

    Python Extract words from a given string

    Cyclic redundancy check in Python

    Finding mean, median, mode in Python without libraries

    cos

    Python add suffix / add prefix to strings in a list

    Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

    Python - Move item to the end of the list

    Python - Print list vertically