使用python向MongoDB插入時間字段的操作
看代碼吧~
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插入數(shù)據(jù)及設置數(shù)據(jù)類型
安裝 Python MongoDB 驅(qū)動程序
安裝驅(qū)動
pip install pymongo
檢查
在python交互模式中,執(zhí)行下面的語句
import pymongo pymongo.version
創(chuàng)建連接
確定 MongoDB 連接串
使用驅(qū)動連接到 MongoDB 集群只需要指定 MongoDB 連接字符串即可。
mongodb://數(shù)據(jù)庫服務器主機地址:端口號 mongodb://127.0.0.1:27017
初始化數(shù)據(jù)庫連接
import pymongo
client = pymongo.MongoClient('mongodb://127.0.0.1:27017')
數(shù)據(jù)庫操作
初始化數(shù)據(jù)庫和集合
db = client.admin
# 認證,如果沒有設置用戶名和密碼可以忽略此項
db.authenticate('root','password')
# 集合,沒有則創(chuàng)建
collection = db[friend]
# 或
collection = db.friend
# 如果集合名有-存在,在python里識別不了,所以建議用[]的方式
插入一條新的用戶數(shù)據(jù)
插入數(shù)據(jù)
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" }
設置數(shù)據(jù)的類型
mongo有很多種數(shù)據(jù)類型,這里主要說一下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") }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關注官方微信