1

I have a JSON file with some data and want to add date information and then insert the content of this JSON file in mongoDB. The JSON file looks something like this:

[
    {
        "installationTime": "How do I insert a date Object here?",
        "someOtherValues": 0,
        ...
    },
    ...
]

And the insertion in node.js:

const content = await readFileAsync('pathToJSONfile.json');
// readFileAsync is fs.readFile wrapped in a promise
await db.createCollection('testCollection');
await db.collection('testCollection').insert(JSON.parse(content));

My question is: How do I insert a date Object like ISODate("2016-12-18T18:30:00Z") into the JSON file? Her in this forum I found:

"installationTime": { "$date": "2016-12-18T18:30:00Z" }

But then I get an Error from mongoDB key $date must not start with '$'.

Is my approach even possible with a json file and the insert command from the node driver?

2
  • JSON itself has no "types" so all data is either going to be a string or possibly numeric. What you read "in the forum" refers to MongoDB Extended JSON syntax. Now there are "some" libraries that exist which implement their own .parse() method which would accept dates formatted like that. Alternately you could use mongoimport instead, which supports that format. Or just use a plain ISOString, and either replace ( "parse" ) those strings as Date objects yourself, or even update enmasse once present in the collection. Commented May 26, 2017 at 9:36
  • So I'm not writing recommendations, but if I just search for MongoDB Extended JSON, The top result is the official manual page, and shortly thereafter you might find things of interest to use in an application. Commented May 26, 2017 at 9:38

1 Answer 1

3

I now have solved it like this:

Import of node module child_process ...

import { exec } from 'child_process';

... in order to execute shell commands. And insertion of the JSON file with mongoimport:

exec('mongoimport --jsonArray --db tstdb --collection testCollection --file pathToJSONfile.json', (error) => {
  if (error) {
    console.log(`exec error: ${error}`);
  }
});

Then the $date key in the JSON file can be used for importing date objects:

"installationTime": { "$date": "2017-10-01T00:00:00.000Z" },

Now find() shows, that the date is stored as an ISODate Object:

> db.getCollection("feed_in_payments").find()
{ "_id" : ObjectId("592bd66cb3395ba514bc1005"), "installationTime" : ISODate("2000-01-01T00:00:00Z"), ...
Sign up to request clarification or add additional context in comments.

1 Comment

The key "$data" must start with "$" and the date string it must end with timezone, in this case "Z".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.