<jupyter_start><jupyter_text>1. Install PyMongo (if required)<jupyter_code># Instaling PyMongo, this is the interface to connect to MongoDB with Python
! python -m pip install pymongo==3.7.2<jupyter_output>Collecting pymongo==3.7.2
[?25l  Downloading https://files.pythonhosted.org/packages/99/18/b50834fbfd557eaf07985c2a657b03efc691462ecba62d03e32c2fc4f640/pymongo-3.7.2-cp37-cp37m-manylinux1_x86_64.whl (406kB)
[K     |████████████████████████████████| 409kB 3.8MB/s 
[?25hInstalling collected packages: pymongo
  Found existing installation: pymongo 3.11.4
    Uninstalling pymongo-3.11.4:
      Successfully uninstalled pymongo-3.11.4
Successfully installed pymongo-3.7.2<jupyter_text>2. Import PyMongo and establish connectionTo practice MongoDB, you can use a free service with limited storage to train or test your code.Here for the example, I use https://www.clever-cloud.com/en/Other services:https://studio3t.com/knowledge-base/articles/cheap-free-mongodb-hosting/<jupyter_code>import datetime                            # Imports datetime library

import pymongo
from pymongo import MongoClient

# uri (uniform resource identifier) defines the connection parameters 
uri = 'mongodb://u1kkdrchfjim80tclysv:<EMAIL>:27017/brny4kjelauboxl'
# start client to connect to MongoDB server 
client = MongoClient( uri )
client.stats                                # .stats  show details about the client<jupyter_output><empty_output><jupyter_text>3. Basic Database management operations<jupyter_code># Show existing database names
client.list_database_names()
# Set database name to work with. If it doesn't exist, it will be created as soon as one document is added.
db = client.brny4kjelauboxl
# Delete a database
client.drop_database('brny4kjelauboxl')<jupyter_output><empty_output><jupyter_text>4. Basic Collection management operations<jupyter_code># Create a new collection. We can create the collection or leave to MongoDB to create it as soon as a document is generated.
db.create_collection('adressbook')       # Optional collection creation 
# Show Collections. Query returns a Cursor [ ] ,  list it to see the content
list (db.list_collections())
# empty list '[]' means that there are not collections in database
# Set the collection to work with
collection = db.adressbook
collection.insert_one({'name' : 'jordi'})     # Insert one item to create the collection
list (collection.find())                  # Show the existing collections
# Rename a collections
db.adressbook.rename('addressbook')
collection = db.addressbook                   # Set the collection to work with
list (db.list_collections())                  # Show the existing collections
# Delete collection
db.drop_collection('addressbook')<jupyter_output><empty_output><jupyter_text>5. Basic Collection operations 5.1 Query Operators - Create Read Update Delete  (one document)  5.1.1 Create a document with:  insert_one() To insert a document can be done using: insert_one and JavaScript notation  { 'attributeName1'  :  'content1', 'attributeName2'  :  'content2', ... }<jupyter_code>#@title Contact
 
Name = "Jordi " #@param {type:"string"}
Age = 34 #@param {type:"slider", min:10, max:80, step:1}
Gender = "Male" #@param ["Male", "Female"]
Likes_Python = "Yes" #@param ["Yes", "No"]
if Likes_Python is "Yes":
  Likes_Python = True
else:
  Likes_Python = False
 
 
#@markdown Address
Street = "Torrent de l'Olla" #@param {type:"string"}
Number = 70 #@param {type:"integer"}
City = "Barcelona" #@param {type:"string"}
PostalCode = "08012" #@param {type:"string"}
data = {  'name' : Name ,                                    # String 
          'age' : Age,                                       # Integer
          'gender' : Gender,                                 # String 
          'likes_python' : Likes_Python,                     # Boolean
          'address': {
              'street' : Street,                             # String ( special character with escape \ )
              'number' : Number,                             # Integer
              'city' : City,                                 # String 
              'floor' : None,                                # Null 
              'postalcode' : PostalCode,                     # String containing a number
              },
          'favouriteFruits': ['banana','pineapple','orange'] # Array        
       }
 
insert_result = collection.insert_one( data)
insert_result.acknowledged    # Confirms that insert is successful
insert_result.inserted_id     # Shows the document ID<jupyter_output><empty_output><jupyter_text>5.1.2 Read document with:  find() To read a document can be done using: find and JavaScript notation  {  'attribute1 containing the key'  :  'key1 to find' }<jupyter_code>list ( collection.find() )                                      # gets all data of collection
list ( collection.find( {'_id' : insert_result.inserted_id } ))  # Find the inserted document using the objectID
list ( collection.find( {'name' : Name } ))                     # find, can use one key or more 
list ( collection.find( {'address.city' : City } ))             # find, can use one key or more 
list ( collection.find().limit(1) )                             # gets a Limited set of documents
list ( collection.find().skip(1) )                              # gets all documents skipping first<jupyter_output><empty_output><jupyter_text>5.1.3 Update a document with:  update_one()<jupyter_code>## Update an existing document
update_result = collection.update_one( 
    {'name' : Name}, 
    {'$set' : { 'age' : 30 }} ) 

list (collection.find( {'name' : Name } ))

# Alternative : collection.find_one_and_update( {'name' : Name}, {'$set' : { 'age' : 30 }} ) 
update_result.raw_result
## Insert a new document with update, will avoid to crash during insert if document already exist
insert_result = collection.update_one( {'name' : '<NAME>'}, {'$set' : { 'age' : 30 }}, upsert= True )
list (collection.find( {'name' : '<NAME>'} ))
update_result.acknowledged<jupyter_output><empty_output><jupyter_text>5.1.4 Delete a document with:  delete_one()<jupyter_code>delete = collection.delete_one({'name': '<NAME>'})
delete.deleted_count   # informs that 1 document has been deleted
collection.delete_one({'name': Name})<jupyter_output><empty_output><jupyter_text>5.2 Create Read Update Delete  (many document) 5.2.1 Create a document with:  insert_many() To insert many documents can be done using: insert_many and JavaScript notation  { 'attributeDocument1'  :  'content1' } , { 'attributeDocument2'  :  'content2'},{ ... }<jupyter_code>import datetime
collection.insert_many(  [                          # <---- start a list with [
##  Insert Document 1
  {
  'name': '<NAME>',
  'age': 25,
  'likes_python': True,
  'registered': datetime.datetime(2015, 2, 11, 4, 22, 39),
  'address': {
      'street': 'Torrent de l\'Olla',
      'number': 70,
      'floor': None,
      'city': 'Barcelona',
      'postalCode': '08012'
             },
  'height':  1.72,
  'favouriteFruits': ['banana','pineapple','orange']
  },

##  Insert Document 2
  {
  'name': '<NAME>',
  'age': 30,
  'likes_python': True,
  'registered': datetime.datetime(2016, 4, 23, 7, 34, 12),
  'address': {
      'street': 'Numancia',
                                                     ##  missing number
                                                     ##  missing floor
      'city': 'Barcelona',
      'postalCode': '08029'
             },
  'height':  1.56,
  'favouriteFruits': ['lemon','pineapple']
  }
  ]   )                                                   # <---- finalize the list ]<jupyter_output><empty_output><jupyter_text>5.2.2 Read many documents with:  find() To read a document can be done using: find and JavaScript notation  {  'attribute1 containing the key'  :  'key1 to find' }<jupyter_code>list ( collection.find( {'$or': [ {'name': '<NAME>'},{'name': '<NAME>'} ]}))        # find<jupyter_output><empty_output><jupyter_text>5.2.3 Update many documents with:  update_many()<jupyter_code>collection.update_many( {'isActive': True }, {'$set' : { 'isActive': False }} )
list (collection.find( ))                                  # List all documents<jupyter_output><empty_output><jupyter_text>5.2.4 Delete many documents with:  delete_many()<jupyter_code>delete = collection.delete_many({'likes_python': True})    # deletes as many documents as the filter
list (collection.find( ))                                  # List all documents
delete.deleted_count   # items deleted<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12160580524344569, 'fraction_numerical': 0.024929775280898875, 'mean_word_length': 2.928735632183908, 'pattern_counts': {'":': 1, '<': 58, '<?xml version=': 0, '>': 56, 'https://': 3, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 22, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '617309', 'license': 'MIT', 'n_tokens_mistral': 2734, 'n_tokens_neox': 2545, 'n_words': 711, 'path': 'PyMongo.ipynb', 'repo_name': 'therealhaseeb/AI_Project_For_Beginners', 'size': '8654'}