1

I want to insert a date into a MongoDB collection. I am importing my data from a JSON file which I am generating from a python script. The script inserts the date as a string, which is not idea. I have found how to use "date": {$date: "2019-10-11"} if I was inserting via MongoDB document to insert the date as date, but can't see how to do this in python.

So is there a way to change all the "date" fields to a date in my collection (which is called collisions?)

Just to add to this: The image shows what I see in MongoDB compass, is there any way to change the String type on date to ISOdate? [![image][1]][1]

Sample JSON output (single record)

{
    "date": "2019-10-11",
    "borough": "QUEENS",
    "weekday": 5,
    "year": 2019,
    "month": 10,
    "day": 11
}


  [1]: https://i.stack.imgur.com/6PAul.png
Joseph
  • 541
  • 1
  • 4
  • 31
  • I have a few questions here that basically boil down to: can you clarify what the specific goal here is? Is modifying the values in the existing documents acceptable, or are you looking to fix and redo the import? Is the Python script generating the data, importing it, or both? – user20042973 Oct 12 '22 at 20:26
  • @user20042973 - Apologies - didn't get any word there was a comment. If I can figure out how to fix the script - that would be great, however, if there is a way to modify the existing collection to take the date in string format and make it a date in date format, that would also be great. I'm a total newbie to Mongo so wasn't sure how to start this. – Joseph Oct 12 '22 at 21:34
  • JSON does not have a date datype... Does this help? https://stackoverflow.com/questions/41999094/how-to-insert-datetime-string-into-mongodb-as-isodate-using-pymongo – Kartoos Oct 13 '22 at 11:52
  • Unfortunately not :( If I were connecting to mongo direct it would, as I'm going via files it's a pain. I'll either need to do the processing and connecting in python or figure out how to change the data once it is in a collection – Joseph Oct 13 '22 at 13:07

1 Answers1

3

As it turns out the answer was in stackoverflow all along.

Using MongoShell, the following command would work, I was first confused by db.collection as I didn't realise "collection" needed to be the collection you wanted to affect:

db.<COLLECTION NAME>.updateMany(
  {},
  [{ "$set": { "<FIELD TO CHANGE": { "$toDate": "$<FIELD TO CHANGE" } }}]
);

Joseph
  • 541
  • 1
  • 4
  • 31