加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

mongodb python $currentDate操作详解

发布时间:2020-12-13 12:39:47 所属栏目:百科 来源:网络整理
导读:$currentDate操作指定字段的值设置为当前日期,可以是一个日期 或时间戳记。默认类型为Date。 参数如下: {?$currentDate:?{?field1:?typeSpecification1,?...?}?} typeSpecification ?如下: 字段值可以为 一个布尔值: true ,代表当前的日期为 Date 或者

$currentDate操作指定字段的值设置为当前日期,可以是一个日期 或时间戳记。默认类型为Date。

参数如下:

{?$currentDate:?{?<field1>:?<typeSpecification1>,?...?}?}

<typeSpecification>?如下:

  • 字段值可以为一个布尔值:true,代表当前的日期为Date

  • 或者文档明确指定类型,运算符区分大小写,并且仅接受timestamp和date都是小写字母。{ $type: "timestamp" } or { $type: "date" }

通俗来说,要么为true? or??{ $type: "timestamp" } or?{ $type: "date" },这三个参数选择其一。建议使用?{ $type: "timestamp" }?

示例:

创建一个customers的集合

db.customers.insertOne(
???{?_id:?1,?status:?"a",?lastModified:?ISODate("2013-10-02T01:11:18.965Z")?})
???
#?ISODate在python就是datetime

from?datetime?import?datetime

db.customers.insert_one(
????{?"_id":?1,?"status":?"a",?"lastModified":?datetime.strptime("2020-02-06?16:11:18","%Y-%m-%d?%H:%M:%S")?}
????)

修改其数据,下面操作更新lastModified字段为当前日期,同时新增字段cancellation.date为当前的时间戳,新增cancellation.reason="user request",更新status="D"。

db.customers.update_one(
???{?"_id":?1?},???{
?????"$currentDate":?{
????????"lastModified":?True,????????"cancellation.date":?{?"$type":?"timestamp"?}
?????},?????"$set":?{
????????"cancellation.reason":?"user?request",????????"status":?"D"
?????}
???})

查询修改后的结果

db.customers.find().pretty()

修改后数据如下:

{
?'_id':?1,?
?'status':?'D',?
?'lastModified':?datetime.datetime(2020,?2,?6,?8,?24,?41,?746000),?
?'cancellation':?
????{'date':?Timestamp(1580977481,?1),?
?????'reason':?'user?request'}}

注意:

使用date创建的时间是utc时间

参考:

https://docs.mongodb.com/manual/reference/operator/update/currentDate/index.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读