如何在Mongodb中给当前时间戳加上1毫秒?

pkwftd7m  于 2023-03-01  发布在  Go
关注(0)|答案(3)|浏览(279)

我需要给我的集合中的所有对象增加1毫秒,我特别关注created_date,比如:

{
  _id: 'd751b295-6597-4a0b-bd64-89b0fbaac812',
  yada: { type: 'yada', id: 'nkfsh000136' },
  audit: {
    created_at: '2022-10-03T09:09:22.672144670Z'
  },
  type: 'yada',
  payload: {
    encounter: {
      provider: {
        first_name: 'yada',
        last_name: 'Doublecheck',
        npi: '1366553539'
      },
      appointment: {
        scheduled: '2022-10-03T09:04:10.588Z',
        start: '2022-09-19T15:04:05Z',
        end: '2022-09-19T15:14:03Z',
        duration: '955'
      },
      codes: { icd10: [ 'R21' ] },
      pharmacy: 'HEB Pharmacy yada #77 (001)'
    }
  },
  vendor: 'yada'
}
s5a0g9ez

s5a0g9ez1#

您可以在更新查询中使用$inc和$toDate运算符向集合中所有文档的created_at字段添加一毫秒,从而更新该字段。以下是使用pymongo的示例代码段:

from pymongo import MongoClient
from datetime import datetime, timedelta

# Connect to the MongoDB server
client = MongoClient()

# Select the database and collection
db = client['your_database_name']
collection = db['your_collection_name']

# Define the update query
update_query = { '$inc': { 'audit.created_at': timedelta(milliseconds=1) } }

# Update all documents in the collection
collection.update_many({}, update_query)
06odsfpq

06odsfpq2#

规范的方法是使用$dateAdd

db.collection.update({},
[
  {
    $set: {
      "audit.created_at": {
        "$dateAdd": {
          "startDate": {
            $toDate: "$audit.created_at"
          },
          "unit": "millisecond",
          "amount": 1
        }
      }
    }
  }
])

Mongo Playground

zy1mlcev

zy1mlcev3#

(编辑)作者使用的是v4.0.0,它既不支持$update管道,也不支持$toDate。假设性能和/或事务性不是一个大问题,这可以在客户端完成:

db.foo.find().forEach(function(doc) {
    var q = new ISODate(doc['audit']['created_at']);
    q.setMilliseconds(1 + q.getMilliseconds())
    rc = db.foo.updateOne({_id:doc['_id']}, {$set: {'audit.created_at':q.toISOStr\
ing()}});
});

强烈建议您将日期存储为真实的日期时间类型。

相关问题