App下載

python怎么向MongoDB插入時(shí)間字段

猿友 2021-08-03 10:26:19 瀏覽數(shù) (3090)
反饋

MongoDB是一個(gè)比較常見的非關(guān)系型數(shù)據(jù)庫(kù),在很多地方都有引用。很多小伙伴也會(huì)用它來進(jìn)行數(shù)據(jù)的存儲(chǔ)。但是普通的文本和數(shù)據(jù)在存儲(chǔ)上比較簡(jiǎn)單,而時(shí)間字段卻是與它們不同的,新手可能會(huì)對(duì)此感到疑惑,那么接下來這篇文章我們就來介紹python怎么操作MongoDB插入時(shí)間字段吧。

看代碼吧~

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()

補(bǔ)充:python連接mongodb插入數(shù)據(jù)及設(shè)置數(shù)據(jù)類型

安裝 Python MongoDB 驅(qū)動(dòng)程序

安裝驅(qū)動(dòng)

pip install pymongo

檢查

在python交互模式中,執(zhí)行下面的語句

import pymongo
pymongo.version

創(chuàng)建連接

確定 MongoDB 連接串

使用驅(qū)動(dòng)連接到 MongoDB 集群只需要指定 MongoDB 連接字符串即可。

mongodb://數(shù)據(jù)庫(kù)服務(wù)器主機(jī)地址:端口號(hào)
mongodb://127.0.0.1:27017

初始化數(shù)據(jù)庫(kù)連接

import pymongo
client = pymongo.MongoClient('mongodb://127.0.0.1:27017')

數(shù)據(jù)庫(kù)操作

初始化數(shù)據(jù)庫(kù)和集合

db = client.admin
# 認(rèn)證,如果沒有設(shè)置用戶名和密碼可以忽略此項(xiàng)
db.authenticate('root','password')
# 集合,沒有則創(chuàng)建
collection = db[friend]
# 或
collection = db.friend
# 如果集合名有-存在,在python里識(shí)別不了,所以建議用[]的方式

插入一條新的用戶數(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è)置數(shù)據(jù)的類型

mongo有很多種數(shù)據(jù)類型,這里主要說一下int64和日期時(shí)間

int64,依賴bson

pip install bson

日期時(shí)間,依賴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") }

以上就是python怎么操作MongoDB插入時(shí)間字段的全部?jī)?nèi)容,希望能給大家一個(gè)參考,也希望大家多多支持W3Cschool。



0 人點(diǎn)贊