skip to Main Content

time: { $currentDate: { $type: "timestamp" } } });

It’s not working for insert()

can you help me, anyone?

2

Answers


  1. The $currentDate is an update operator so you will need to use one of the MongoDB Date() and Datetime methods. Here is an example a few you can choose:

    db.collection.insertOne(
        {  
            name: "bob",
            age: 20,
            time: ISODate(), // ISODate("2024-02-01T08:00:30.429Z"),
            time2: new Date(), // ISODate("2024-02-01T08:00:30.429Z"),
            time3: new Timestamp() // Timestamp({ t: 1706774430, i: 1 })
        }
    );
    

    See HERE for a full working example.

    Login or Signup to reply.
  2. If it is a document with only a few fields, you could do an upsert with the $currentDate operator so that the timestamp is determined at the MongoDB server:

    db.collection.update({
      _id: "123"
    },
    {
      $setOnInsert: {
        anotherField: 123
      },
      $currentDate: {
        timestamp: true
      }
    },
    {
      upsert: true
    })
    

    It is important not to match another document with the filter (first parameter); otherwise, this document would receive a new timestamp and no new document would be created.

    See this mongoplayground.

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