使用python向MongoDB插入时间字段的操作
import pymongofrom dateutil import parserdateStr = '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 pymongopymongo.version创建连接
确定 MongoDB 连接串
使用驱动连接到 MongoDB 集群只需要指定 MongoDB 连接字符串即可。
mongodb://数据库服务器主机地址:端口号mongodb://127.0.0.1:27017
初始化数据库连接
import pymongoclient = 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 admindb.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 bsonfrom dateutil import parseraa = { '_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') }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持好吧啦网。
相关文章:
