#!/usr/bin/env python#Coding:utf-8#Filename:mongodb.py fromPymongoImportmongoclient,ascending,descendingImportdatetime#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":d Atetime.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 ()PrintDoc#Query by ObjectIdPrint 'Query is:', Db.posts.find_one ({"_id":p ost_id})#querying for more than one doc forPostinchdb.posts.find ():PrintPost#CountingPrint 'Total count is:', Db.posts.count ()#Range QueriesD=datetime.datetime (2014,8,9,12) forPostinchDb.posts.find ({"Date":{"$GT":D}). Sort ("author"): Print 'GT is:', Post#Indexing#before indexingPrintDb.posts.find ({"Date":{"$GT":D}). Sort ("author"). Explain () ["cursor"]PrintDb.posts.find ({"Date":{"$GT":D}). Sort ("author"). Explain () ["nscanned"]#After indexingDb.posts.create_index ([("Date", descending), ("author", Ascending)])PrintDb.posts.find ({"Date":{"$GT":D}). Sort ("author"). Explain () ["cursor"]PrintDb.posts.find ({"Date":{"$GT":D}). Sort ("author"). Explain () ["nscanned"]#Remove all IndexesDb.posts.drop_indexes ()