首页 > 代码库 > Python mongoDB 的简单操作
Python mongoDB 的简单操作
#!/usr/bin/env python# coding:utf-8# Filename:mongodb.pyfrom pymongo import MongoClient,ASCENDING,DESCENDINGimport datetime# connection with mongoclientclient=MongoClient()# getting a databasedb=client.test# getting a collectioncollection=db.posts# documentspost={"author":"Mike", "test":"My first blog post!", "tags":["mongodb","python","pymongo"], "date":datetime.datetime.utcnow()}# inserting a documentpost_id=collection.insert(post)print ‘posts id is:‘,post_idprint ‘collection_names is:‘,db.collection_names()# getting a single documentdoc=db.posts.find_one()print doc#query by objectIdprint ‘query is:‘, db.posts.find_one({"_id":post_id})# querying for more than one docfor post in db.posts.find(): print post# countingprint ‘total count is:‘,db.posts.count()# range queriesd=datetime.datetime(2014,8,9,12)for post in db.posts.find({"date":{"$gt":d}}).sort("author"): print ‘gt is:‘,post# Indexing# before indexingprint db.posts.find({"date":{"$gt":d}}).sort("author").explain()["cursor"]print db.posts.find({"date":{"$gt":d}}).sort("author").explain()["nscanned"]# after indexingdb.posts.create_index([("date",DESCENDING),("author",ASCENDING)])print db.posts.find({"date":{"$gt":d}}).sort("author").explain()["cursor"]print db.posts.find({"date":{"$gt":d}}).sort("author").explain()["nscanned"]# remove all indexesdb.posts.drop_indexes()
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。