@songying
2018-10-15T09:39:46.000000Z
字数 1792
阅读 2104
pymongo
pip install pymongoimport pymongo
from pymongo import MongoClientclient = MongoClient()client = MongoCLient('localhost', 27017)client = MongoCLient('mongodb://localhost:27017/')
db = client.test_databasedb = Client['test-database']
collection = db.test_collectioncollection = db['test-collection']
collection = db.postspost_id = collection.insert_one(post).inserted_id
_id是pymongo自动生成的一列数字。
.insert_one(字典) : 插入文档
.inserted_id: 你刚刚插入到集合中的文档的id
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)}]result = collection.insert_many(new_posts)result.inserted_ids
db.collection_names(include_system_collections=False)
show(collection)
collection.update()# 参数1: 数据库中某一条记录的一个字段的值。它是一个“代号”, 保证我们在数据库中能找到它。# 参数2: 更新后打数据,字典格式dic['blog'] = '哒哒的博客一般人是不会知道的'collection.update({'name': "傻瓜哒哒"}, dic)
collection.update({'name': '刀塔传奇'}, {'$set': {"name": "可爱的Mongodb"}})collection.update_one({'name': '刀塔传奇'}, {'$set': {"name": "可爱的Mongodb"}})
collection.update_many({'name': '刀塔传奇'}, {'$set': {"name": "可爱的Mongodb"}})
collection.remove({'name': '可爱的Mongodb'})
collection.find_one()# 返回值:成功:文档内容失败: Nonecollection.find_one({"author": "Mike"})# 寻找含有该键值对的文档
_id来查询文档
posts.find_one({"_id": post_id})# 注意此时打post_id并不是string格式
当你从web框架中获取一个文档的_id时,它是string类型,我们需要先将其转化为ObjectId
document = client.db.collection.find_one({'_id': ObjectId(post_id)})
collection.find() # 集合中所有符合条件打文档collection.find({"age": {'$gt': 20}})
大于: $gt
小于 : $lt
大于等于: $gte
小于等于:$lte
不等于 : $ne
collection.find({"author": "Mike"}).count()collection.count() # 查询collection中到底有多少条记录
