#!/usr/bin/env Python #-*-coding:utf-8-*-"" "Use Pymongo Library operations MongoDB Database" "Import Pymongo # 1. Connect to the database server, get the client object MONGO _client=pymongo. Mongoclient (' localhost ', 27017) # 2. Get database Objects Db=mongo_client.mydb # db=mongo_client[' MyDB '] # 3. Get Collection Object my_collection= Db.mycollection # my_collection=db[' mycollection '] print ("--*50) # Insert document tom={' name ': ' Tom ', ' age ': ' Sex ': ' Male ', ' Hobbies ': [' eat ', ' sleep ', ' Beat Peas ']} alice={' name ': ' Alice ', ' age ': ' Sex ': ' female ', ' hobbies ': [reading ', ' running ', ' playing guitar ']} tom_id=my_
Collection.insert (Tom) Alice_id=my_collection.insert (Alice) print (tom_id) print (alice_id) print ("--*50) # Query document Cursor=my_collection.find () print (Cursor.count ()) # Get the number of documents for the item in Cursor:print (item) Print ("--" *50) # Modify Document M Y_collection.update ({' name ': ' Tom '},{' $set ': {' hobbies ': ' Learn from Alice, ' run with Alice ', ' learn to play guitar with Alice '}}) for item in My_ Collection.find (): Print (item) print ("--*50) # Delete Document # My_collection.remove ({' name ': ' Tom '},{' Justone ': 0}) My_collect Ion.remove () for item in My_collection.find (): PRint (item)
Run results
/usr/bin/python3.5/home/brandon/pythonprojects/myspider/data store/Save to database/mongodb/use Pymongo library to manipulate MongoDB database. py —————————
——————————————————————————————————————————————————————————————————————————————————————————— 5a56344bfc275a13874a807e 5a56344bfc275a13874a807f ——————————————————————————————————————————————————————————————————————————————————————— ————————————— 2 {' name ': ' Tom ', ' sex ': ' Male ', ' _id ': ObjectId (' 5a56344bfc275a13874a807e '), ' hobbies ': [' eat ', ' sleep ', ' beat Peas '], ' Age ': {' name ': ' Alice ', ' sex ': ' Female ', ' _id ': ObjectId (' 5a56344bfc275a13874a807f '), ' hobbies ': [' reading ', ' running ', ' playing guitar '], ' age ' : ———————————————————————————————————————————————————————————————————————————————————————————————————— {' Name ': ' Tom ', ' sex ': ' Male ', ' _id ': ObjectId (' 5a56344bfc275a13874a807e '), ' hobbies ': [' Learn from Alice ', ' Run with Alice ', '] Learning to play guitar, ' age ': {' name ': ' Alice ', ' Sex ': ' Female ', ' _id ': ObjectId (' 5a56344bfc275a13874a807f '), ' hobbies ': [' reading ', ' running Step ', ' play guitar '], ' age ': ————————————————————————————————————————————————————————————————————————————————————————————————————