'Inputting data with JSON files in MongoDB
This may be a trivial question for most, but I am beginning to learn MERN stack and am unfamiliar with MongoDB.
I am having trouble creating my own database with MongoDB Compass. I am trying to create a database that includes class times for a project that displays class schedules. The database needs to have the date that the class began as well as the date the class ends.
the problem I am running into is that I am creating this database using a JSON file and plan to import that file to MongoDB Compass, and I am unable to use ISODate(). Is there an alternative way to record times in a JSON file or perhaps a more efficient method to input this data other than using JSON files?
Solution 1:[1]
You have a few options here.
- If you have control over the input file, change your ISODate strings to use MongoDB EJSON, e.g.
OLD: {"startTime":"2022-01-25T00:37:49.593Z", "endTime":"2022-01-25T01:37:49.593Z"}
NEW: {"startTime":{"$date":"2022-01-25T00:37:49.593Z"}, "endTime":{"$date":"2022-01-25T01:37:49.593Z"}}
Both Compass and mongoimport are sensitive to EJSON and will perform the appropriate type conversion upon load.
- Convert the dates after loading into Compass by creating a two stage aggregation pipeline. The trick with
$mergeis to use themergeaction. You only need to do this once. The whole collection will be updated with ISO datestrings converted into real MongoDB datetimes.
$addFields:
{
startTime: {$dateFromString: {dateString: "$startTime"}}
}
$merge:
{
into: 'foo',
on: '_id',
whenMatched: 'merge'
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Buzz Moschetti |
