在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
看代码吧~import pymongo from dateutil import parser dateStr = "2019-05-14 01:11:11" myDatetime = parser.parse(dateStr) client = pymongo.MongoClient(host="127.0.0.1", port=27017) db = client["test"] db.ceshi.insert({"date": myDatetime}) client.close() 补充:python连接mongodb插入数据及设置数据类型 安装 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") } 以上为个人经验,希望能给大家一个参考,也希望大家多多支持极客世界。 |
2022-05-27
2022-05-27
2022-05-27
2022-05-27
2022-05-27
请发表评论