当前位置:Gxlcms > mysql > PyMongo笔记

PyMongo笔记

时间:2021-07-01 10:21:17 帮助过:34人阅读

安装 $ 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"}})

人气教程排行