0

I am 1 day old to MongoDB so bear with me. I am simply trying to output a simple query to a *.json file. The query is:

db.collection.findOne() // collection is substituted with the correct collection name, the query preludes 'use db' command where db is substituted with correct db name

Then, in reference to this article and a bunch of other SO answers, I perform the following query:

--eval "printjson(db.results.findOne())" >> sample.json

I even created a blank sample.json file, and I experimented --eval with -eval etc. I keep getting:

SyntaxError: missing ;before statement (shell):1

I add semi colons at arbitrary places, but I have no idea why this doesn't work for me.

Can anybody point out what I am missing here?

Complete sequence of commands:

mongo
use dbname
--eval "printjson(db.collectionName.findOne())" >> sample.json

P.S: The command db.collectionName.findOne() does give me an output

Parijat Kalia
  • 4,929
  • 10
  • 50
  • 77

1 Answers1

0

--eval should be passed as an argument to "mongo" command. I tried below and it worked:

C:\>mongo localhost:27017/dbname --eval "printjson(db.results.findOne())" >> sample.json
Anand Jayabalan
  • 12,294
  • 5
  • 41
  • 52
  • wait, I am in the mongo command line shell. (unix environment), but I'll try the above – Parijat Kalia Mar 20 '14 at 18:31
  • ha, that did it for me. I did not realize that I had to be outside of the mongo shell environment for the output to be added to a file. Is there noway I can do this while I am inside the mongo shell ? – Parijat Kalia Mar 20 '14 at 18:33
  • 1
    I don't think it's do-able, but using [load()](http://docs.mongodb.org/manual/reference/method/load/) you can run JS files from within the Mongo shell. I would recommend you to post a separate question and someone from the community might suggest an approach. – Anand Jayabalan Mar 20 '14 at 18:40