2

I'd like to know if there is any command or tool to export mongo collections in JSON extended mode instead of strict mode which is the default mode.

Any suggestion will be welcome.

Thanks!

Alex Guerreiro
  • 135
  • 2
  • 13

1 Answers1

1

The strict mode export supported by mongoexport and mongoimport is extended JSON:

Strict mode representations of BSON types conform to the JSON RFC. Any JSON parser can parse these strict mode representations as key/value pairs; however, only the MongoDB’s internal JSON parser also recognizes the type information conveyed by the format.

There is also a looser representation for the mongo shell which is JSON-like, but allows syntax which is not valid JSON. For example, the shell syntax allows unquoted string values which represent helper functions (such as ISODate()) for extended data types.

Extended JSON:

{
   "_id":{
       "$oid":"55d39fac2ba0663a655bee54"
   },
   "day":{
        "$date":"2015-08-18T21:12:12.945Z"
   }
}

mongo shell syntax (JSON-like):

{
  "_id": ObjectId("55d39fac2ba0663a655bee54"),
  "day": ISODate("2015-08-18T21:12:12.945Z")
}

Exporting from the mongo shell

If you really want to export a collection in mongo shell syntax, you can pipe the output to a file.

This format will only be understood by the mongo shell, and you will likely run into limitations if you are trying to print a large collection:

mongo server:port/dbname --eval "printjson(db.collection.find().toArray())"

The standard command line tools for importing/exporting collections as JSON are mongoimport and mongoexport. These generally aren't suitable for database backups -- see the MongoDB manual for supported Backup and Recovery tutorials.

Stennie
  • 63,885
  • 14
  • 149
  • 175
  • This command works fine. is there any way to print the result to a file? Thank you! – Alex Guerreiro Aug 20 '15 at 21:43
  • @AlexGuerreiro Yes, just redirect the output in your terminal session, eg: `mongo server:port/dbname --quiet --eval "printjson(db.collection.find().toArray())" > output.json`. Note: I added "--quiet" which will suppress any connection messages. This option is probably not needed if you have a recent (3.x) version of `mongo`, but some older shell versions would print unwanted output to stdout. – Stennie Aug 20 '15 at 22:58