对象已移动

可在此处找到该文档 Python and MongoDB Database Development – New Self New Life
New Self New Life
No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices
New Self New Life
No Result
View All Result
Home Softwares

Python and MongoDB Database Development

by admin
3 years ago
in Softwares
Python: How to Use Tkinter’s Grid Manager
Share on FacebookShare on Twitter


As talked about within the first a part of this collection: Python Database Programming with MongoDB, the Python module PyMongo is required for Python to have the ability to talk with a MongoDB database. To put in this, use the command on the Home windows Command Immediate:

pip3 set up pymongo

Putting in PyMongo ought to produce an output related to what’s proven beneath:

PyMongo Module

Determine 1 – Putting in the PyMongo Module

Relying on the Python configuration, a further module named dnspython can also be crucial:

pip3 set up dnspython

Python and MongoDB modules

Determine 2 – Putting in the dnspython module

Learn: Prime On-line Programs to Be taught Python Programming

Methods to Insert Information in MongoDB with Python

The code beneath will create 15 randomly generated Artists and two Albums for every of them:

# bad-band-name-maker-nosql.py

import sys
import random
import pymongo

part1 = ["The", "Uncooked", "Appealing", "Larger than Life", "Drooping", "Unwell", "Atrocious", "Glossy", "Barrage", "Unlawful"]
part2 = ["Defeated", "Hi-Fi", "Extraterrestrial", "Adumbration", "Limpid", "Looptid", "Cromulent", "Unsettled", "Soot", "Twinkle"]
part3 = ["Brain", "Segment", ""Audio"", "Legitimate Business", ""Bob"", "Sound", "Canticle", "Monsoon", "Preserves", ""Cacophony""]

part4 = ["Cougar", "Lion", "Lynx", "Ocelot", "Puma", "Jaguar", "Panther"]
part5 = ["Fodder", "Ersatz Goods", "Leftovers", "Infant Formula", "Mush", "Smoothie", "Milkshakes"]


def predominant(argv):
  # Connect with the RazorDemo database.
  shopper = pymongo.MongoClient("mongodb+srv://yourUser:[email protected]/RazorDemo?retryWrites=true&w=majority", 
    serverSelectionTimeoutMS=5000)
  artistsCollection = shopper["RazorDemo"]["Artists"]
  albumsCollection = shopper["RazorDemo"]["Albums"]

  # Generate 15 dangerous band names, and attempt to maintain them distinctive.
  previousNames = ""
  nameCount = 0
  artistJson = []
  whereas (nameCount < 16):
    rand1 = random.randrange(0, 9)
    rand2 = random.randrange(0, 9)
    rand3 = random.randrange(0, 9)
    badName = part1[rand1] + ' ' + part2[rand2] + ' ' + part3[rand3]
    
    # Not like with SQL-oriented databases, MongoDB permits for the insertion of a number of paperwork in a single assertion.
    # On this case, the code will construct a JSON record of all of the band names to be inserted in a one fell swoop.
    if ("|" + previousNames + "|").discover("|" + badName + "|") == -1: 
      #print ("Band identify [" + str(nameCount) + "] is [" + badName + "]")
      # Do not forget to flee citation marks!
      
      jsonEntry = { "artist_name" : badName }
      artistJson.append(jsonEntry)
      
      # As a result of there aren't any international key guidelines, the album names could be created 
      # and dedicated to the database earlier than the artist names have been created.
      albumJson = []
      for y in vary(1, 3):
        rand4 = random.randrange(0, len(part4))
        rand5 = random.randrange(0, len(part5))
        
        # No checks for uniqueness right here. Peter Gabriel had 4 self-titled
        # albums in any case.
        albumName = part4[rand4] + " " + part5[rand5]
        albumEntry = { "artist_name" : badName, "album_name" : albumName }
        albumJson.append(albumEntry)
      print (albumJson)
      albumsCollection.insert_many(albumJson)
      
      # Creates a bar-delimited record of beforehand used names.
      # MongoDB expects the appliance to implement information integrity guidelines.
      if previousNames == "":
        previousNames = badName
      else:
        previousNames = previousNames + "|" + badName
      nameCount = 1 + nameCount
    else:
      print ("Discovered a reproduction of [" + badName + "]")

  print (artistJson)
  artistsCollection.insert_many(artistJson)

  # Shut the Connection
  shopper.shut()
  return 0

if __name__ == "__main__":
	predominant(sys.argv[1:])

Itemizing 6 - Creating Random Information

One fascinating statement about this code, no less than in comparison with the SQL-oriented examples in Python Database Programming with SQL Specific for Novices is that it’s a lot less complicated, as there is no such thing as a further SQL element. The JSON features are already part of Python and the one MongoDB-related command is the insert_many() features which might be executed after every dataset is created. Much more handy, these instructions match the identical syntax in Python that’s used within the MongoDB Shell.

From a safety standpoint, points like SQL Injection merely don’t exist in such code, not simply because there is no such thing as a SQL being executed, however completely no code in any respect is being handed into the database. The Python Checklist performance additionally takes care of issues like escaping citation marks.

As a substitute of exhibiting the output within the Command Immediate window, one other piece of code might be used to question the database as a substitute.

Learn: Methods to Kind Lists in Python

Validating the Inserts with Python

The code beneath will question the MongoDB database for the insert actions made above utilizing Python:

# bad-band-name-display-nosql.py

import sys
import pymongo

def predominant(argv):
  # Connect with the RazorDemo database.
  shopper = pymongo.MongoClient("mongodb+srv://yourUser:[email protected]/RazorDemo?retryWrites=true&w=majority", 
    serverSelectionTimeoutMS=5000)
  artistsCollection = shopper["RazorDemo"]["Artists"]
  albumsCollection = shopper["RazorDemo"]["Albums"]

  print ("Albums:")
  artists = artistsCollection.discover()
  
  for artist in artists:
    print (str(artist["artist_name"]))
    albumQuery = { "artist_name": {"$eq" : str(artist["artist_name"])} }
    albumsForThisArtist = albumsCollection.discover(albumQuery)
    for album in albumsForThisArtist:
      print ("t" + str(album["album_name"]))

  # Shut the Connection
  shopper.shut()
  return 0

if __name__ == "__main__":
	predominant(sys.argv[1:])

Itemizing 7 - Validating the Insert Actions

The output beneath accommodates the preliminary paperwork created additional up within the doc:

MongoDB Validate Inserts

Determine 3 – Validating the Inserts

Querying MongoDB Information with Python

The code above could be tailored into an interactive software to question the information with person enter. MongoDB gives a robust textual content search software for its collections, however so as to allow it, textual content indexes should be created on the collections to be searched:

db.Artists.createIndex({artist_name: "textual content"})

db.Albums.createIndex({artist_name: "textual content", album_name: "textual content"})

Itemizing 8 - Creating Textual content Indices for every assortment

Observe that MongoDB solely permits for one textual content index per assortment. Making an attempt to create one other index for a unique node in a group will trigger an error. The output of those instructions in MongoDB Shell is beneath:

MongoDB Indices

Determine 4 – Including Textual content Indices

Whereas the textual content search software can carry out all kinds of loopy matching logic involving common expressions and partial matches with closeness rating, the instance beneath will stick to easy matching, so as to illustrate the proof of idea:

# bad-band-name-query-nosql.py

import sys
import pymongo

def predominant(argv):
  searchValue = enter("Enter one thing: ")
  # Cap the size at one thing cheap. The primary 20 characters.
  searchValue = searchValue[0:20]
  # Set the search worth to decrease case so we are able to carry out case-insensitive matching:
  searchValue = searchValue.decrease()

  # Connect with the RazorDemo database.
  shopper = pymongo.MongoClient("mongodb+srv://yourUser:[email protected]/RazorDemo?retryWrites=true&w=majority", 
    serverSelectionTimeoutMS=5000)
  artistsCollection = shopper["RazorDemo"]["Artists"]
  albumsCollection = shopper["RazorDemo"]["Albums"]

  matchedArtists = "";
  artists = artistsCollection.discover( { "$textual content":{ "$search": searchValue} })

  for artist in artists:
    matchedArtists = matchedArtists + "t" + str(artist["artist_name"]) + "rn"
  if "" == matchedArtists:
    print ("No matched artists.")
  else:
    print ("Matched Artists:")
    print (matchedArtists)

  
  albums = albumsCollection.discover( { "$textual content":{ "$search": searchValue} })
  matchedAlbums = ""
  for album in albums:
    matchedAlbums = matchedAlbums + "t" + str(album["artist_name"]) + " - " + str(album["album_name"]) + "rn"
    
  if "" == matchedAlbums:
    print ("No matched albums.")
  else:
    print ("Matched Albums:")
    print (matchedAlbums)
    
  # Shut the Connection
  shopper.shut()
  return 0

if __name__ == "__main__":
	predominant(sys.argv[1:])


Itemizing 9 - Querying the information

Observe that no conversion of the information popping out of MongoDB was wanted to match it to the lowercase model of the search time period.

Closing Ideas on Python and MongoDB Improvement

For builders who’ve been coding towards SQL-oriented database servers and databases, the leap to noSQL can really feel like scaling a really steep studying curve, however by mapping acquainted SQL database ideas to their NoSQL counterparts, it turns into rather less uncomfortable of a climb. Such builders could even be shocked on the lack of “primary” “options” comparable to international key enforcement or the expectation that it’s the utility and never the database that’s anticipated to implement information integrity guidelines. For very seasoned SQL-oriented database builders, even the mere considered such concepts nearly looks like programming heresy!

However NoSQL databases like MongoDB add many different options that make the change in pondering value it. Not needing to fret about yet one more model of SQL that’s “simply totally different sufficient” to be annoying, or not having to consider points like SQL injection, with the ability to insert a number of data, err, paperwork of information securely with out the trouble of “hundreds” of particular person statements, and even perhaps entertaining the “loopy” concept that having the appliance do the information enforcement shaves off an enormous chunk of utility improvement efforts makes all of it definitely worth the consideration.

Learn extra Python programming tutorials and software program improvement guides.



Source link

Tags: DatabaseDevelopmentMongoDBPython
Previous Post

Mickey Gilley’s Biggest Hits – Billboard

Next Post

Check Out the Most Surprising Celeb Transformations of the Week

Related Posts

Meta and UK Government launch ‘Open Source AI Fellowship’
Softwares

Meta and UK Government launch ‘Open Source AI Fellowship’

by admin
July 12, 2025
Supervised vs Unsupervised Learning: Machine Learning Overview
Softwares

Supervised vs Unsupervised Learning: Machine Learning Overview

by admin
July 10, 2025
Minor update (2) for Vivaldi Desktop Browser 7.5
Softwares

Minor update (2) for Vivaldi Desktop Browser 7.5

by admin
July 9, 2025
20+ Best Free Food Icon Sets for Designers — Speckyboy
Softwares

20+ Best Free Food Icon Sets for Designers — Speckyboy

by admin
July 8, 2025
Luna v1.0 & FlexQAOA bring constraint-aware quantum optimization to real-world problems
Softwares

Luna v1.0 & FlexQAOA bring constraint-aware quantum optimization to real-world problems

by admin
July 7, 2025
Next Post
Check Out the Most Surprising Celeb Transformations of the Week

Check Out the Most Surprising Celeb Transformations of the Week

What is the best college movie? : movies

What is the best college movie? : movies

  • Trending
  • Comments
  • Latest
Kanye West entry visa revoked by Australia after ‘Heil Hitler’ song release – National

Kanye West entry visa revoked by Australia after ‘Heil Hitler’ song release – National

July 3, 2025
CBackup Review: Secure and Free Online Cloud Backup Service

CBackup Review: Secure and Free Online Cloud Backup Service

September 18, 2021
Every Van Halen Album, Ranked 

Every Van Halen Album, Ranked 

August 12, 2024
I Tried Calocurb For 90 Days. Here’s My Review.

I Tried Calocurb For 90 Days. Here’s My Review.

January 8, 2025
Bones: All Of Brennan’s Interns, Ranked

Bones: All Of Brennan’s Interns, Ranked

June 15, 2021
Get to Know Ronnie Shacklett – Hollywood Life

Get to Know Ronnie Shacklett – Hollywood Life

December 6, 2023
5 ’90s Alternative Rock Bands That Should’ve Been Bigger

5 ’90s Alternative Rock Bands That Should’ve Been Bigger

April 13, 2025
Clevo CO Review – A Complete Company Details

Clevo CO Review – A Complete Company Details

January 19, 2024
Jeff Lynne Pulls Out of Final ELO Show — See His Statement

Jeff Lynne Pulls Out of Final ELO Show — See His Statement

July 12, 2025
Crypto Billionaire Justin Sun Buys Another $100 Million of Trump’s Memecoin

Crypto Billionaire Justin Sun Buys Another $100 Million of Trump’s Memecoin

July 12, 2025
Paris Haute Couture Week 2025 Best Looks

Paris Haute Couture Week 2025 Best Looks

July 12, 2025
It’s the last day to get up to 50 percent off air fryers, Instant Pots, blenders and more

It’s the last day to get up to 50 percent off air fryers, Instant Pots, blenders and more

July 11, 2025
Hey r/movies! We’re Courtney Stephens and Callie Hernandez, the filmmakers of the recent meta-fictional, experimental feature film INVENTION, that’s now streaming on Mubi. You might also know Callie from La La Land, Alien: Covenant, Blair Witch, Under the Silver Lake, The Endless. Ask us anything!

Hey r/movies! We’re Courtney Stephens and Callie Hernandez, the filmmakers of the recent meta-fictional, experimental feature film INVENTION, that’s now streaming on Mubi. You might also know Callie from La La Land, Alien: Covenant, Blair Witch, Under the Silver Lake, The Endless. Ask us anything!

July 12, 2025
Meta and UK Government launch ‘Open Source AI Fellowship’

Meta and UK Government launch ‘Open Source AI Fellowship’

July 12, 2025
Best Amazon Prime Day 2025 Alternative Sales: Walmart, Target & More

Best Amazon Prime Day 2025 Alternative Sales: Walmart, Target & More

July 11, 2025
Michael Strahan’s extended silence raises questions during GMA absence

Michael Strahan’s extended silence raises questions during GMA absence

July 11, 2025
New Self New Life

Your source for entertainment news, celebrities, celebrity news, and Music, Cinema, Digital Lifestyle and Social Media and More !

Categories

  • Celebrity
  • Cinema
  • Devices
  • Digital Lifestyle
  • Entertainment
  • Music
  • Social Media
  • Softwares
  • Uncategorized

Recent Posts

  • Jeff Lynne Pulls Out of Final ELO Show — See His Statement
  • Crypto Billionaire Justin Sun Buys Another $100 Million of Trump’s Memecoin
  • Paris Haute Couture Week 2025 Best Looks
  • Home
  • Disclaimer
  • DMCA
  • Privacy Policy
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites. slotsfree  creator solana token

No Result
View All Result
  • Home
  • Entertainment
  • Celebrity
  • Cinema
  • Music
  • Digital Lifestyle
  • Social Media
  • Softwares
  • Devices

Copyright © 2021 New Self New Life.
New Self New Life is not responsible for the content of external sites.

New Self New Life