This article mainly introduces Python's MongoDB module PyMongo operation methods, including data addition, deletion, query, modification, index, and other basic operations, if you want to import modules, refer to the following before you start:
>>> import pymongo
Next, you must install and start the local mongodb server.
The Connection established on the Consumer Client:
Client = your client ('localhost', 27017) # or client = your client ('mongodb: // localhost: 27017 /')
Obtain the database:
>>> Db = client. test_database # Or >>> db = client ['test-database']
Get a data set:
Collection = db. test_collection # Or collection = db ['test-collection']
Data in MongoDB uses Json-style documents:
>>> import datetime>>> post = {"author": "Mike",... "text": "My first blog post!",... "tags": ["mongodb", "python", "pymongo"],... "date": datetime.datetime.utcnow()}
Insert a document:
>>> posts = db.posts>>> post_id = posts.insert_one(post).inserted_id>>> post_idObjectId('...')
Find a piece of data:
>>> posts.find_one(){u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}>>> posts.find_one({"author": "Mike"}){u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}>>> posts.find_one({"author": "Eliot"})>>>
Search through ObjectId:
>>> post_idObjectId(...)>>> posts.find_one({"_id": post_id}){u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}
Do not convert the ObjectId type to String:
>>> post_id_as_str = str(post_id)>>> posts.find_one({"_id": post_id_as_str}) # No result>>>
What if you have a post_id string?
from bson.objectid import ObjectId# The web framework gets post_id from the URL and passes it as a stringdef get(post_id): # Convert from string to ObjectId: document = client.db.collection.find_one({'_id': ObjectId(post_id)})
Insert multiple entries:
>>> new_posts = [{"author": "Mike",... "text": "Another post!",... "tags": ["bulk", "insert"],... "date": datetime.datetime(2009, 11, 12, 11, 14)},... {"author": "Eliot",... "title": "MongoDB is fun",... "text": "and pretty easy too!",... "date": datetime.datetime(2009, 11, 10, 10, 45)}]>>> result = posts.insert_many(new_posts)>>> result.inserted_ids[ObjectId('...'), ObjectId('...')]
Search for multiple data entries:
>>> for post in posts.find():... post...{u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}{u'date': datetime.datetime(2009, 11, 12, 11, 14), u'text': u'Another post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'bulk', u'insert']}{u'date': datetime.datetime(2009, 11, 10, 10, 45), u'text': u'and pretty easy too!', u'_id': ObjectId('...'), u'author': u'Eliot', u'title': u'MongoDB is fun'}
Of course, you can also restrict the search conditions:
>>> for post in posts.find({"author": "Mike"}):... post...{u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}{u'date': datetime.datetime(2009, 11, 12, 11, 14), u'text': u'Another post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'bulk', u'insert']}
Obtain the number of data entries in the Set:
>>> posts.count()
Or the number of data entries that meet certain search conditions:
>>> posts.find({"author": "Mike"}).count()
Range search, for example, time range:
>>> d = datetime.datetime(2009, 11, 12, 12)>>> for post in posts.find({"date": {"$lt": d}}).sort("author"):... print post...{u'date': datetime.datetime(2009, 11, 10, 10, 45), u'text': u'and pretty easy too!', u'_id': ObjectId('...'), u'author': u'Eliot', u'title': u'MongoDB is fun'}{u'date': datetime.datetime(2009, 11, 12, 11, 14), u'text': u'Another post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'bulk', u'insert']}
$ Lt means less.
How to create an index? For example, the following query:
>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"]u'BasicCursor'>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["nscanned"]
Index creation:
>>> from pymongo import ASCENDING, DESCENDING>>> posts.create_index([("date", DESCENDING), ("author", ASCENDING)])u'date_-1_author_1'>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"]u'BtreeCursor date_-1_author_1'>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["nscanned"]
Connection Aggregation
>>> Account = db. Account # Or >>> account = db ["Account"]
View all cluster names
>>> db.collection_names()
View A aggregated record
>>> db.Account.find_one() >>> db.Account.find_one({"UserName":"keyword"})
View aggregated Fields
>>> db.Account.find_one({},{"UserName":1,"Email":1}){u'UserName': u'libing', u'_id': ObjectId('4ded95c3b7780a774a099b7c'), u'Email': u'libing@35.cn'} >>> db.Account.find_one({},{"UserName":1,"Email":1,"_id":0}){u'UserName': u'libing', u'Email': u'libing@35.cn'}
View multiple aggregated records
>>> for item in db.Account.find(): item >>> for item in db.Account.find({"UserName":"libing"}): item["UserName"]
View aggregated record statistics
>>> db.Account.find().count() >>> db.Account.find({"UserName":"keyword"}).count()
Sort aggregate query results
>>> Db. account. find (). sort ("UserName") # The default value is ascending> db. account. find (). sort ("UserName", pymongo. ASCENDING) # ASCENDING> db. account. find (). sort ("UserName", pymongo. DESCENDING) # DESCENDING order
Multi-column sorting of clustered query results
>>> db.Account.find().sort([("UserName",pymongo.ASCENDING),("Email",pymongo.DESCENDING)])
Add record
>>> db.Account.insert({"AccountID":21,"UserName":"libing"})
Modify record
>>> db.Account.update({"UserName":"libing"},{"$set":{"Email":"libing@126.com","Password":"123"}})
Delete record
>>> Db. Account. remove () -- delete all >>> db. Test. remove ({"UserName": "keyword "})