一.实例
# 类似 MySQL 以下语句,并更新时间
INSERT INTO ... ON DUPLICATE KEY UPDATE ...
# 第一次执行时,生成 create_time 和 update_time
# 第二次执行时,更新 update_time
二.Mongo Shell
方式一.
db.student.updateOne(
{ sno: 1 },
{
$setOnInsert: { create_time: new Date() },
$set: { sname: "qbit", update_time: new Date() }
},
{
upsert: true
}
)
方式二(currentDate)
/*
约等于上面的语句。
通常下面的语句在新建 document 时,
update_time 会比 create_time 晚一点。
因为 new Date() 是 js 函数,在客户端生成;
currentDate 获取的是服务器时间
*/
db.student.updateOne(
{ sno: 1 },
{
$currentDate: {
update_time: true
},
$setOnInsert: { create_time: new Date() },
$set: { sname: "qbit" }
},
{
upsert: true
}
)
三.pymongo
# -*- coding: utf-8 -*-
# @Time : 2022/1/14 9:35
# @Author : Cocktail_py
from datetime import datetime, tzinfo, timedelta
import pytz
import pymongo
from bson.codec_options import CodecOptions
class MongoHelper(object):
def __init__(self, conn_url):
# 设置读取来时间的时区
options = CodecOptions(tz_aware=True, tzinfo=pytz.timezone('Asia/Shanghai'))
self.db = pymongo.MongoClient(conn_url, maxPoolSize=None).get_database(codec_options=options)
def insert_or_update(self, table_name: str,
data_dict: dict,
):
"""
插入或更新
:param table_name: MongoDB 集合名
:param data_dict: 带_id主键的数据
:return:
"""
coll = self.db[table_name]
# 0 区
dt0 = datetime.utcnow()
_id = data_dict.get("id", "")
if not _id:
raise Exception("数据存储需要唯一id")
data_dict['update_time'] = dt0
update_dict = {'$set': data_dict, '$setOnInsert': {'create_time': dt0, 'delete_time': 0}}
return coll.update_one({"_id": _id}, update_dict, upsert=True)
def get_all(self, table_name, data_dict={}, field_dict={}, sort_field="create_time", sort_type=pymongo.DESCENDING,
limit=0):
"""
获取相应集合的数据
:param table_name: MongoDB 集合名
:param data_dict: 查询条件
:param field_dict: 需要返回的字段 {"A":1,"B":0} 返回A字段,返回字段中排出B字段
:param sort_field: 排序字段
:param sort_type: 排序类型
:param limit: 条数
:return:
"""
coll = self.db[table_name]
_id = data_dict.get("id", "")
if _id:
data_dict["_id"] = _id
return list(coll.find(data_dict, field_dict).sort(sort_field, sort_type).limit(limit=limit))
def count(self, table_name, data_dict={}):
"""
计算当前集合数量
:param table_name:
:param data_dict:
:return:
"""
coll = self.db[table_name]
_id = data_dict.get("id", "")
if _id:
data_dict["_id"] = _id
return coll.count_documents(data_dict)
if __name__ == "__main__":
username = 'admin' # 用户名
password = '123456' # 密码
host = '127.0.0.1'
port = 27017
dbname = 'dw'
conn_url = f'mongodb://{username}:{password}@{host}:{port}/{dbname}?authSource=admin'
# 设置读取来时间的时区
mongo = MongoHelper(conn_url=conn_url)
table_name = "table_name "
# 获取时间大于'2022-01-14 10:59:06的值
date = datetime.strptime('2022-01-14 10:59:06', '%Y-%m-%d %H:%M:%S')
class UTC(tzinfo):
"""UTC"""
def __init__(self, offset=0):
self._offset = offset
def utcoffset(self, dt):
return timedelta(hours=self._offset)
def tzname(self, dt):
return "UTC +%s" % self._offset
def dst(self, dt):
return timedelta(hours=self._offset)
year = date.year
month = date.month
day = date.day
hour = date.hour
minute = date.minute
second = date.second
create_time = datetime(year, date.month, date.day, date.hour, minute, second, 000000, tzinfo=UTC(8))
documents = mongo.get_all(table_name, data_dict={"create_time": {"$gte": create_time}},
field_dict={}, limit=10)
for doc in documents:
doc['create_time'] = doc['create_time'].strftime('%Y-%m-%d %H:%M:%S')
doc['update_time'] = doc['update_time'].strftime('%Y-%m-%d %H:%M:%S')
print(doc)
参考:
https://segmentfault.com/a/1190000022435473