Insert date time using Data API in Python

Hi,

We need to use Time Series feature in MongoDB & currently we are using MongoDB Data API for adding values in our Database.

We need to add time in the body in the POST method but we are getting errors as

"Failed to insert document: FunctionError: Failed to insert documents: bulk write exception: write errors: ['time' must be present and contain a valid BSON UTC datetime value]"

Code:

import datetime as dt
url = "XXXX/app/data-ozscf/endpoint/data/v1/action/insertOne"
var data = {}
data["time"] = dt.datetime.now()
payload = json.dumps({
    "collection": "time-series",
    "database": "db",
    "dataSource": "Cluster0",
    "document": data,
})
headers = {
    'Content-Type': 'application/json',
    'Access-Control-Request-Headers': '*',
    'api-key': "XXX", 
}
response = requests.request("POST", url, headers=headers, data=payload, verify=False)

without the time it is working perfectly fine, Please help

Could you try using MongoDB Extended JSON which preserves type information: https://www.mongodb.com/docs/atlas/api/data-api/#specify-the-request-data-format

from bson import json_util
...
payload = json_util.dumps(...)  # <--- use bson.json_util.dumps to encode MongoDB Extended JSON

headers = {
    'Content-Type': 'application/ejson',  # <--- use ejson
    'Access-Control-Request-Headers': '*',
    'api-key': "XXX", 
}
2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.