120

So I do not know much about MongoDB. I have RoboMongo using which I connect to a MongoDB. What I need to do is this - there is a collection in that MongoDB. I want to export the data from that collection so that I can save it into a file.

I used the interface to open the data from the collection as text and did a Ctrl + A and pasted into a text file. However, I found that not all data is copied and also that there were many comments in the text data which naturally breaks the JSON.

I am wondering if RoboMongo has a Export As JSON facility so that I can do a clean export.

Any pointers are appreciated!

Penny Liu
  • 7,720
  • 5
  • 40
  • 66
Undefined Variable
  • 3,670
  • 6
  • 34
  • 63
  • You want to export particular collections or full db? – Ramesh Murugesan Feb 26 '15 at 05:24
  • 1
    This isn't a current feature of Robomongo, but I've added a feature suggestion in the github issue queue: [Add JSON export](https://github.com/paralect/robomongo/issues/764). There's a general suggestion that [import/export should be integrated](https://github.com/paralect/robomongo/issues/102), but more detailed/practical use cases would be helpful. For example, should this support exporting JSON from a collection, a find query, an aggregation pipeline? Currently your best option is to use the standard `mongoexport` command line tool. – Stennie Feb 26 '15 at 05:35
  • 1
    @Stennie - thank you for your comment. I guess in answer to your question - from a customer experience viewpoint, it does not really matter. In most other DB interfaces, the flow is that you run a query (with or without critera), get a set of results. Right click and say "export results as..." So the same should be applicable here. Does not matter if I am exporting an entire collection or a find query. If the result can get displayed in the panel, then it should be exportable. – Undefined Variable Feb 26 '15 at 06:46
  • 1
    Simply you can do this ```mongoexport --uri='mongodb://someUser@mongodb0.example.com:27017/marketing' --collection=contacts --out=contacts.json``` – Naren Jun 08 '20 at 10:40

14 Answers14

90

A Quick and dirty way: Just write your query as db.getCollection('collection').find({}).toArray() and right click Copy JSON. Paste the data in the editor of your choice.

enter image description here

öbl
  • 1,163
  • 9
  • 13
66

You can use tojson to convert each record to JSON in a MongoDB shell script.

Run this script in RoboMongo:

var cursor = db.getCollection('foo').find({}, {});
while(cursor.hasNext()) {
    print(tojson(cursor.next()))
}

This prints all results as a JSON-like array.

The result is not really JSON! Some types, such as dates and object IDs, are printed as JavaScript function calls, e.g., ISODate("2016-03-03T12:15:49.996Z").

Might not be very efficient for large result sets, but you can limit the query. Alternatively, you can use mongoexport.

Florian Winter
  • 3,381
  • 1
  • 33
  • 52
  • 4
    It outputs not valid json. Just json-serialized records one by one – ruX Aug 23 '16 at 16:53
  • For many use-cases, one can use `tojson(db.getCollection(...).find(...)["_batch"])` to output the entirety of the current batch obtained from the server. – Yuval Aug 30 '18 at 14:22
  • @Yuval You mean literally `["_batch"]`? Can you give an example how to use this? I tried this with Robo 3T 1.2.1, but it only says "Script executed successfully, but there are no results to show". – Florian Winter Aug 30 '18 at 14:46
  • 7
    @FlorianWinter That was just from random findings from fiddling around. A better solution is `tojson(db.getCollection(...).find(...).toArray())`. – Yuval Aug 31 '18 at 01:33
  • @Yuval Nice! That's the easiest solution then, much better than mine. Consider posting it as an answer. (Or edit mine, but then I would get all the credit that you deserve, which would be somewhat unfair...) – Florian Winter Aug 31 '18 at 08:36
  • @Yuval A downside of your approach may be that the entire collection is loaded into memory, then converted to JSON. Or that it only outputs part of the collection. I did not test it thoroughly. Mine outputs the whole collection and only keeps one document in memory per iteration. – Florian Winter Aug 31 '18 at 08:44
  • Your last statement is incorrect: your approach appends each record to the variable `records` hence all records are kept in memory. There is nothing much to test, it's just more concise code I thought I would share. – Yuval Sep 04 '18 at 13:19
  • @Yuval Thanks for the heads-up. I have improved the script. – Florian Winter Sep 04 '18 at 15:08
  • This gives me "Script executed successfully, but there are no results to show" – Shanika Ediriweera Oct 04 '19 at 04:12
  • @Florian Winter - Follow up question on your Note : How to convert BinData and ISODate type functions to actual values(the way it is represented in GUI) while export? – Priya Agarwal Feb 07 '20 at 07:22
  • @PriyaAgarwal I'm not sure I fully understand your question, but if it is a follow-up question, then I would suggest asking it as a new question. You will be more likely to get help on here if you do so. – Florian Winter Feb 07 '20 at 10:35
33

Robomongo's shell functionality will solve the problem. In my case I needed couple of columns as CSV format.

var cursor = db.getCollection('Member_details').find({Category: 'CUST'},{CustomerId :1,Name :1,_id:0})

while (cursor.hasNext()) {
    var record = cursor.next();   
    print(record.CustomerID + "," + record.Name)
}

Output : -------

334, Harison
433, Rechard
453, Michel
533, Pal
kenorb
  • 118,428
  • 63
  • 588
  • 624
Anish Abraham
  • 331
  • 3
  • 4
21

you say "export to file" as in a spreadsheet? like to a .csv?

IMO this is the EASIEST way to do this in Robo 3T (formerly robomongo):

  1. In the top right of the Robo 3T GUI there is a "View Results in text mode" button, click it and copy everything

  2. paste everything into this website: https://json-csv.com/

  3. click the download button and now you have it in a spreadsheet.

hope this helps someone, as I wish Robo 3T had export capabilities

russiansummer
  • 961
  • 10
  • 14
  • This actually helped solve my problem while my IntelliJ data connection is broken. Sad I have to jump through hoops like this in the year 2021, but hey, it works. Thank you! – craastad May 04 '21 at 12:52
19

There are a few MongoDB GUIs out there, some of them have built-in support for data exporting. You'll find a comprehensive list of MongoDB GUIs at http://mongodb-tools.com

You've asked about exporting the results of your query, and not about exporting entire collections. Give 3T MongoChef MongoDB GUI a try, this tool has support for your specific use case.

Juan Carlos Farah
  • 3,539
  • 30
  • 40
Tomek
  • 307
  • 1
  • 2
11

Don't run this command on shell, enter this script at a command prompt with your database name, collection name, and file name, all replacing the placeholders..

mongoexport --db (Database name) --collection (Collection Name) --out (File name).json

It works for me.

Vince Bowdren
  • 5,986
  • 2
  • 24
  • 48
8

I don't think robomongo have such a feature. So you better use mongodb function as mongoexport for a specific Collection.

http://docs.mongodb.org/manual/reference/program/mongoexport/#export-in-json-format

But if you are looking for a backup solution is better to use

mongodump / mongorestore
henrily
  • 236
  • 1
  • 5
6

If you want to use mongoimport, you'll want to export this way:

db.getCollection('tables')
  .find({_id: 'q3hrnnoKu2mnCL7kE'})
  .forEach(function(x){printjsononeline(x)});
shapiromatron
  • 424
  • 4
  • 10
5

Expanding on Anish's answer, I wanted something I can apply to any query to automatically output all fields vs. having to define them within the print statement. It can probably be simplified but this was something quick & dirty that works great:

var cursor = db.getCollection('foo').find({}, {bar: 1, baz: 1, created_at: 1, updated_at: 1}).sort({created_at: -1, updated_at: -1});

while (cursor.hasNext()) {
    var record = cursor.next();
    var output = "";
    for (var i in record) {
      output += record[i] + ",";
    };
    output = output.substring(0, output.length - 1);
    print(output);
}
Mark Shust at M.academy
  • 5,533
  • 3
  • 27
  • 45
2

Using a robomongo shell script:

//on the same db
var cursor = db.collectionname.find();

while (cursor.hasNext()) {
    var record = cursor.next();   
    db.new_collectionname.save(record);
}

Using mongodb's export and import command

You can add the --jsonArray parameter / flag to your mongoexport command, this exports the result as single json array.

Then just specify the --jsonArray flag again when importing.

Or remove the starting and ending array brackets [] in the file, then your modified & exported file will import with the mongoimport command without the --jsonArray flag.

More on Export here: https://docs.mongodb.org/manual/reference/program/mongoexport/#cmdoption--jsonArray

Import here: https://docs.mongodb.org/manual/reference/program/mongoimport/#cmdoption--jsonArray

Herald Smit
  • 1,976
  • 18
  • 23
2

Solution:

mongoexport --db test --collection traffic --out traffic.json<br><br>

enter image description here

Where:
database -> mock-server
collection name -> api_defs
output file name -> childChoreRequest.json

Bonifacio2
  • 2,687
  • 4
  • 30
  • 44
amoljdv06
  • 2,008
  • 1
  • 10
  • 16
2

An extension to Florian Winter answer for people looking to generate ready to execute query.

drop and insertMany query using cursor:

{
    // collection name
    var collection_name = 'foo';

    // query
    var cursor = db.getCollection(collection_name).find({});

    // drop collection and insert script
    print('db.' + collection_name + '.drop();');
    print('db.' + collection_name + '.insertMany([');

    // print documents
    while(cursor.hasNext()) {
        print(tojson(cursor.next()));

        if (cursor.hasNext()) // add trailing "," if not last item
            print(',');
    }

    // end script
    print(']);');
}

Its output will be like:

db.foo.drop();
db.foo.insertMany([
{
    "_id" : ObjectId("abc"),
    "name" : "foo"
}
,
{
    "_id" : ObjectId("xyz"),
    "name" : "bar"
}
]);
Shaharyar
  • 11,393
  • 3
  • 39
  • 59
1

I had this same issue, and running script in robomongo (Robo 3T 1.1.1) also doesn't allow to copy values and there was no export option either. The best way I could achieve this is to use mongoexport, if mongodb is installed on your local, you can use mongoexport to connect to database on any server and extract data

To connect to Data on remote server, and csv output file, run the following mongoexport in your command line

mongoexport --host HOSTNAME --port PORT --username USERNAME --password "PASSWORD" --collection COLLECTION_NAME --db DATABASE_NAME --out OUTPUTFILE.csv --type=csv --fieldFile fields.txt

fieldFile: helps to extract the desired columns, ex: contents of fields.txt can be just:

userId

to only extract values of the column 'userId'

Data on remote server, json output file:

mongoexport --host HOST_NAME --port PORT --username USERNAME --password "PASSWORD" --collection COLECTION_NAME --db DATABASE_NAME --out OUTPUT.json

this extracts all fields into the json file

data on localhost (mongodb should be running on localhost)

mongoexport --db DATABASE_NAME --collection COLLECTION --out OUTPUT.json

Reference: https://docs.mongodb.com/manual/reference/program/mongoexport/#use

0
  1. make your search
  2. push button view results in JSON mode
  3. copy te result to word
  4. print the result from word
Soroush Chehresa
  • 3,630
  • 1
  • 10
  • 23