安装 Python MongoDB 驱动程序
-
安装驱动
pip install pymongo
-
检查
-
在python交互模式中,执行下面的语句
import pymongo pymongo.version
-
创建连接
-
确定 MongoDB 连接串
- 使用驱动连接到 MongoDB 集群只需要指定 MongoDB 连接字符串即可。
- mongodb://数据库服务器主机地址:端口号
- mongodb://127.0.0.1:27017
-
初始化数据库连接
import pymongo client = pymongo.MongoClient('mongodb://127.0.0.1:27017')
数据库操作
-
初始化数据库和集合
db = client.admin # 认证,如果没有设置用户名和密码可以忽略此项 db.authenticate('root','password') # 集合,没有则创建 collection = db[friend] # 或 collection = db.friend # 如果集合名有-存在,在python里识别不了,所以建议用[]的方式
插入一条新的用户数据
-
插入数据
new_friend = { "_id": "4519678129565659554", "user_id": "4519678129565659555", "friend_user_id": "4519678129565659556", "remark": "", "add_time": "2020-07-07T00:39:31.961Z" } collection.insert_one(new_friend)
-
在mongo shell中查看
use admin db.auth("root","password") show tables; db.friend.find({}) -- { "_id" : "4519678129565659554", "user_id" : "4519678129565659555", "friend_user_id" : "4519678129565659556", "remark" : "", "add_time" : "2020-07-07T00:39:31.961Z" }
-
设置数据的类型
mongo有很多种数据类型,这里主要说一下int64和日期时间
-
int64,依赖
bson
pip install bson
-
日期时间,依赖
parser
pip install python-dateutil
import bson from dateutil import parser aa = { "_id": bson.int64.Int64("4519678129565659557"), "user_id": bson.int64.Int64("4519678129565659558"), "friend_user_id": bson.int64.Int64("4519678129565659559"), "remark": "", "add_time": parser.parse("2020-07-07T00:39:31.961Z"), "_class": "com.aihangxunxi.common.entity.mongo.FriendRelationShip" } collection.insert_one(aa)
-
在mongo shell中查看
db.friend.find({}) -- { "_id" : NumberLong("4519678129565659557"), "user_id" : NumberLong("4519678129565659558"), "friend_user_id" : NumberLong("4519678129565659559"), "remark" : "", "add_time" : ISODate("2020-07-07T00:39:31.961Z") }