当前位置:首页 > PHP教程 > PHP总结归纳

PyMongo笔记

安装 $ pip install pymongo//指定pymongo版本$ pip install pymongo==2.1.1//upgrade现有的版本$ pip install --upgrade pymongo 使用 from pymongo import mongoclientconnection = mongoclient()#指定host和portconnection = mongoclient('localhost', 27

安装

$ pip install pymongo //指定pymongo版本 $ pip install pymongo==2.1.1 //upgrade现有的版本 $ pip install --upgrade pymongo

使用

from pymongo import mongoclient connection = mongoclient() #指定host和port connection = mongoclient('localhost', 27017) db = connection.test_database

插入

>>> import datetime >>> post = {"author": "mike", ... "text": "my first blog post!", ... "tags": ["mongodb", "python", "pymongo"], ... "date": datetime.datetime.utcnow()} >>> posts = db.posts >>> post_id = posts.insert(post) >>> post_id objectid('...') #多个插入 >>> new_posts = [{"author": "mike", ... "text": "another post!", ... "tags": ["bulk", "insert"], ... "date": datetime.datetime(2009, 11, 12, 11, 14)}, ... {"author": "eliot", ... "title": "mongodb is fun", ... "text": "and pretty easy too!", ... "date": datetime.datetime(2009, 11, 10, 10, 45)}] >>> posts.insert(new_posts) [objectid('...'), objectid('...')]

查找

>>>posts.find_one({"author": "mike"}) {u'date': datetime.datetime(...), u'text': u'my first blog post!', u'_id': objectid('...'), u'author': u'mike', u'tags': [u'mongodb', u'python', u'pymongo']} #若不存在则没有返回值 #按id查找 >>>posts.find_one({"_id": post_id}) {u'date': datetime.datetime(...), u'text': u'my first blog post!', u'_id': objectid('...'), u'author': u'mike', u'tags': [u'mongodb', u'python', u'pymongo']} #注意post_id为objectid类型而不是string, 如果是string则会找不到 #所以当从请求的url中获取id后必须把string类型转换成objectid类型再使用 from bson.objectid import objectid # the web framework gets post_id from the url and passes it as a string def get(post_id): # convert from string to objectid: document = connection.db.collection.find_one({'_id': objectid(post_id)})

count

>>> posts.count() 3 >>> posts.find({"author": "mike"}).count() 2

sort和limit

#-1为倒序 db.posts.find().sort({'author':-1}).limit(10)

update

db.posts.update({"_id": post_id}, {"$set": {"author":"mark"}})

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!