`
2014马年
  • 浏览: 118681 次
  • 性别: Icon_minigender_1
  • 来自: 晋中
社区版块
存档分类
最新评论

pymongo 使用简单使用

阅读更多

 

1.新建连接

 

 

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
#client = MongoClient('mongodb://localhost:27017/')
db = client.test_database
#db = client['test-database']

 2.插入

 

 

db.posts.insert(postjson)
#datetime.datetime.utcnow() 时间用这个方法

 3.查看有哪些表

 

 

print db.collection_names()
[u'system.indexes,u'posts']

4.使用 find_one() 查找一个确定的文档,或者只想返回第一个匹配的文档。找不到返回None

 

5.查找_id

 

from bson.objectid import ObjectId
find_one({'_id': ObjectId(post_id)})

 

 

6.编码问题

bson 是字符是utf8编码的str,所以pymongo只支持utf8的数据,普通的str类型会直接存,unicode类型会首先转成utf8字符串

 

7.批量插入

 

a=[{..},{...}]
db.posts.insert(a)
#结果[ObjectId('...'), ObjectId('...')]

8.查询

 

 

for post in posts.find({"author": "Mike"}):
...   post

 

posts.count()
posts.find({"author": "Mike"}).count()

 

d = datetime.datetime(2009, 11, 12, 12) 
for post in posts.find({"date": {"$lt": d}}).sort("author"):
    print post

 类似的高级查询:

 

$gt $gte $in $lt $lte $ne $nin

$or $and $not $nor

$existe $type

$mod $regex $text $where

$all $elemMatch $size $slice 

查询具体参照:http://docs.mongodb.org/manual/reference/operator/query/

更新参照:http://docs.mongodb.org/manual/reference/operator/update/

 

9.索引

 

posts.create_index([("date", DESCENDING), ("author", ASCENDING)])

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics