carte blanche
carte blanche

Reputation: 11476

How to store inserted time automatically in mongoDB?

I am trying to automatically save the time of insertion into mongodb as 'created_on' : new Date(), below is JSON object but running into an error, is there a way this can be done?please provide guidance

data = {
    "orgRadar" : 36353275,
    'created_on' : new Date(),
    "clonedRadars" : [ 
        {
            "clonedRadar" : 39851508,
            "clonedStatus" : "PASS",
            "clonedStatusfailReason" : "N/A",
            "updateStatus" : "PASS",
            "updatedFailedReason" : "N/A"
        }, 
        {
            "clonedRadar" : 39394842,
            "clonedStatus" : "PASS",
            "clonedStatusfailReason" : "N/A",
            "updateStatus" : "FAIL",
            "updatedFailedReason" : "Category Required"
        }
    ]
}

Error:

  File "mongodb_insertdata.py", line 39
    'created_on' : new Date(),
                          ^
SyntaxError: invalid syntax

Upvotes: 1

Views: 68

Answers (2)

user
user

Reputation: 4811

I'm assuming that you're writing in Python given the tag and little bit of stack trace you copied. new Date() isn't going to work in Python, since that's JavaScript:

Python 2.7.10 (default, Feb  7 2017, 00:08:15)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> new Date()
  File "<stdin>", line 1
    new Date()
           ^
SyntaxError: invalid syntax
>>>

You should probably use something like:

import datetime

data = {
    "orgRadar" : 36353275,
    "created_on" : datetime.datetime.utcnow(),
    "clonedRadars" : [ 
        {
            "clonedRadar" : 39851508,
            "clonedStatus" : "PASS",
            "clonedStatusfailReason" : "N/A",
            "updateStatus" : "PASS",
            "updatedFailedReason" : "N/A"
        }, 
        {
            "clonedRadar" : 39394842,
            "clonedStatus" : "PASS",
            "clonedStatusfailReason" : "N/A",
            "updateStatus" : "FAIL",
            "updatedFailedReason" : "Category Required"
        }
    ]
}

If using Python, you should refer to the PyMongo documentation instead of the MongoDB documentation, since those will match your language bindings. PyMongo datetime examples and information can be found here.

Upvotes: 2

Jsandesu
Jsandesu

Reputation: 105

You can try $currentDate, since it corresponds to your type which is Date.

You can read more from the documentation here https://docs.mongodb.com/manual/reference/operator/update/currentDate/

Upvotes: 1

Related Questions