mongodb python $currentDate操作详解
$currentDate操作指定字段的值设置为当前日期,可以是一个日期 或时间戳记。默认类型为Date。 参数如下: {?$currentDate:?{?<field1>:?<typeSpecification1>,?...?}?}
通俗来说,要么为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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |