Basic usage of PyMongo

Keywords: MongoDB Database Python

1. First, download and install MongoDB and MongoDB Compass
The download address of MongoDB is: https://www.mongodb.com/download-center/community
The installation process can refer to: http://www.runoob.com/mongodb/mongodb-window-install.html
Note: during the installation process, it is prompted to install MongoDB Compass, which needs to be unchecked and installed later. The installation address is: https://www.mongodb.com/download-center/compass
Compass can help me to understand the data structure and see the effect of the command directly.

The new version of MongoDB does not need to install MongoDB service. You can run it directly in bin folder
mongod.exe, and then run mongo.exe. Enter db in the pop-up interface, and then you can pop up ah test. Basically, there is no problem running it


2. Basic use
2.1 create connection

from pymongo import MongoClient
client=MongoClient('localhost',27017)
client = MongoClient('mongodb://localhost:27017/')#Another way to create

2.2
Create database

#The test database is the name of the database defined by ourselves. After executing this command, the system will create a new database named test database
db = client.test_database
db = client['test-database']#Another way to create

2.3 create a collection

#As above, test collection is also a collection name defined by ourselves. The system will create a collection named test collection under test data.
collection = db.test_collection
collection = db['test-collection']#Another way to create

2.4 creating documents

post = {"author": "Mike", "tags": ["mongodb", "python", "pymongo"]}
collection.insert(post)
#If the command is executed again, an error will be reported as follows
#pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection
#But if you use collection.insert({'url':"http://...","html": "..."}), you can insert it many times



2.4.1 creating documents

#In this way, a new collection named web page will be created directly.
db.webpage.insert({'url':"http://....",'html':'............'})



If the command is executed again, an error will not be prompted, but the id will be different.

db.webpage.insert({'url':"http://....",'html':'............'})


2.5 find one

collection.find_one()
#Results: {'_id': objectid ('5cb7ecbd924f6d376cab760f '),'author':'Mike ',' tags': ['mongodb ',' Python ',' pymongo ']}
db.webpage.find_one()
#{'_id': ObjectId('5cb7f845924f6d376cab7614'), 'url': 'http://....', 'html': '............'}
collection.find_one({"author": "Mike"})
#{'_id': ObjectId('5cb7ecbd924f6d376cab760f'), 'author': 'Mike', 'tags': ['mongodb', 'python', 'pymongo']}

#To query by id, you need to return the id parameter when inserting data
posts = db.posts
post_id = posts.insert_one(post).inserted_id#Return id parameter for later query
posts.find_one({"_id": post_id})
#{'_id': ObjectId('5cb7ecbd924f6d376cab760f'), 'author': 'Mike', 'tags': ['mongodb', 'python', 'pymongo']}
#Or use the following method, if you need to use objectId
from bson.objectid import ObjectId
collection.find_one('_id': ObjectId('5cb7ecbd924f6d376cab760f'))


2.6 querying multiple documents

import pprint
for doc in db.webpage.find():
    pprint.pprint(doc)
    """
    {'_id': ObjectId('5cb7f845924f6d376cab7614'),
 'html': '............',
 'url': 'http://....'}
{'_id': ObjectId('5cb7f89c924f6d376cab7615'),
 'html': '............',
 'url': 'http://....'}
    """

2.7 create id

import pymongo
result = db.posts.create_index([('user_id', pymongo.ASCENDING)],unique=True) 
list(db.posts.index_information())
#Result: [', user's ID'1'] one more user is'1
db.posts.insert({'naqwme':"wu","gen34der":"male",'user_id':12})
#Returned result: ObjectId('5cb804ed924f6d376cab7618 ')


2.8 delete a document

db.posts.delete_one({"author":"M0ike"})#In this case, Mike I modified it in compass, and changed it into M0ike.

Before deleting

2.9 delete a collection

db.drop_collection('webpage')
#Results: {'NS':' test_database. Webpage ',' nindexeswas': 1, 'OK': 1.0}



2.10 delete a database

client.drop_database("test_database")

Posted by csudhoff on Tue, 26 Nov 2019 09:17:58 -0800