如何将 1 毫秒添加到 Mongodb 中的当前时间戳?

问题描述 投票:0回答:3

我需要为我集合中的所有对象添加 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'
}
mongodb pymongo
3个回答
1
投票

您可以通过在更新查询中使用 $inc 和

created_at
运算符向其添加一毫秒来更新集合中所有文档的
$toDate
字段。这是一个使用
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)

0
投票

规范的方法是使用

$dateAdd
.

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

Mongo 游乐场


0
投票

来自mongosh:

db.foo.updateMany({}, [
    {$addFields: {'audit.created_at': {$add:[1,{$toDate: '$audit.created_at'}]} }}
], {multi:true})
© www.soinside.com 2019 - 2024. All rights reserved.