skip to Main Content

I need to add 1 millisecond to all objects in my collection. I’m looking at created_date specifically. Such as this:

    {
  _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'
}

3

Answers


  1. You can update the created_at field of all documents in your collection by adding one millisecond to it using the $inc and $toDate operators in an update query. Here’s an example code snippet using 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)
    
    Login or Signup to reply.
  2. The canonical way to do it is using $dateAdd.

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

    Mongo Playground

    Login or Signup to reply.
  3. (Edited) The author is on v4.0.0 which supports neither $update pipelines nor $toDate. Assuming performance and/or transactionality is not a huge concern, this can be done on the client side:

    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()}});
    });
    
    

    It is always highly recommended that you store dates as real datetime types.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search