首页 > 代码库 > 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()