标签:date name utf-8 语句 odi client cli dex code
学习笔记,用作数据库查询,原文参考
1 #!/usr/bin/env python 2 #coding:utf-8 3 # Author: --<qingfengkuyu> 4 # Purpose: MongoDB的使用 5 # Created: 2014/4/14 6 #32位的版本最多只能存储2.5GB的数据(NoSQLFan:最大文件尺寸为2G,生产环境推荐64位) 7 8 import pymongo 9 import datetime 10 import random 11 12 #创建连接 13 conn = pymongo.Connection(‘10.11.1.70‘,27017) #现在用pymongo.MongoClient连接 14 #连接数据库 15 db = conn.study 16 #db = conn[‘study‘] 17 18 #打印所有聚集名称,连接聚集 19 print u‘所有聚集:‘,db.collection_names() 20 posts = db.post 21 #posts = db[‘post‘] 22 print posts 23 24 #插入记录 25 new_post = {"AccountID":22,"UserName":"libing",‘date‘:datetime.datetime.now()} 26 new_posts = [{"AccountID":22,"UserName":"liuw",‘date‘:datetime.datetime.now()}, 27 {"AccountID":23,"UserName":"urling",‘date‘:datetime.datetime.now()}]#每条记录插入时间都不一样 28 29 posts.insert(new_post) 30 #posts.insert(new_posts)#批量插入多条数据 31 32 #删除记录 33 print u‘删除指定记录:\n‘,posts.find_one({"AccountID":22,"UserName":"libing"}) 34 posts.remove({"AccountID":22,"UserName":"libing"}) 35 36 #修改聚集内的记录 37 posts.update({"UserName":"urling"},{"$set":{‘AccountID‘:random.randint(20,50)}}) 38 39 #查询记录,统计记录数量 40 print u‘记录总计为:‘,posts.count(),posts.find().count() 41 print u‘查询单条记录:\n‘,posts.find_one() 42 print posts.find_one({"UserName":"liuw"}) 43 44 #查询所有记录 45 print u‘查询多条记录:‘ 46 #for item in posts.find():#查询全部记录 47 #for item in posts.find({"UserName":"urling"}):#查询指定记录 48 #for item in posts.find().sort("UserName"):#查询结果根据UserName排序,默认为升序 49 #for item in posts.find().sort("UserName",pymongo.ASCENDING):#查询结果根据UserName排序,ASCENDING为升序,DESCENDING为降序 50 for item in posts.find().sort([("UserName",pymongo.ASCENDING),(‘date‘,pymongo.DESCENDING)]):#查询结果根据多列排序 51 print item 52 53 #查看查询语句的性能 54 #posts.create_index([("UserName", pymongo.ASCENDING), ("date", pymongo.DESCENDING)])#加索引 55 print posts.find().sort([("UserName",pymongo.ASCENDING),(‘date‘,pymongo.DESCENDING)]).explain()["cursor"]#未加索引用BasicCursor查询记录 56 print posts.find().sort([("UserName",pymongo.ASCENDING),(‘date‘,pymongo.DESCENDING)]).explain()["nscanned"]#查询语句执行时查询的记录数
标签:date name utf-8 语句 odi client cli dex code
原文地址:http://www.cnblogs.com/dahu-daqing/p/6670604.html