MongoDB的层级为 database -->collection --> document
安装MongoDB,启动mongo服务
安装Python的mongo模块
pip install pymongo
安装完后查看
pip list
模块引用
import pymongo
建立连接
import pymongo from pymongo import MongoClient client = MongoClient(‘localhost‘,27017) #client = MongoClient(‘mongodb://localhost:27017‘)
访问数据库
当前所使用的数据库test的users
db = client.test users = db.users #或者db = client[‘users‘]
插入文档
文档就是一行,集合就是一个表
一个insert_one()
user1 = {"name":"li8","age":8} rs = users.insert_one(user1) print(‘one insert:{0}‘.format(rs.inserted_id))
多个 insert_many()
user2 = {"name":"li9","age":9} user3 = {"name":"li10","age":10} user4 = {"name":"li11","age":11} user5 = {"name":"li12","age":12} new_result = users.insert_many([user2, user3, user4, user5]) print(‘Multiple users: {0}‘.format(new_result.inserted_ids))
检索文档
一个find_one()
usertmp = users.find_one({"age":33}) print(usertmp)
多个find()
rs = users.find({‘age‘: 33}) for tmp in rs: print(tmp)
高级查询
rs = users.find({‘age‘:{"$lt":30}}).sort("name") for tmp in rs: print(tmp)
统计数量
print(users.count())
加索引
from pymongo import ASCENDING, DESCENDING print(users.create_index([("age", DESCENDING), ("name", ASCENDING)]))
MongoEngine是一个对象文档映射器(ODM),相当于一个基于SQL的对象关系映射器(ORM)
MongoEngine提供的抽象是基于类的,创建的所有模型都是类
安装
pip install mongoengine
使用
from mongoengine import * connect(‘test‘, host=‘localhost‘, port=27017) import datetime class Users(Document): name = StringField(required=True, max_length=200) age = IntField(required=True) users = Users.objects.all() for u in users: print("name:",u.name,",age:",u.age)
保存
from mongoengine import * connect(‘test‘, host=‘localhost‘, port=27017) import datetime class Users(Document): name = StringField(required=True, max_length=200) age = IntField(required=True) user1 = Users( name=‘zz‘, age= 11 ) user1.save() print(user1.name) user1.name = ‘zz11‘ user1.save() print(user1.name)
时间: 2024-11-03 03:31:05