1

I do not get an output while passing the ObjectId even where there is a match and when I run the same command from the mongo shell it works.. what could be the problem?

mongo myDB --eval 'db.myUserDocColl.find({"_id" : ObjectId("55fd20104ead737a83540a91")},{name:1,email:1,mobileNumber:1,"_id":0});'

The output is

MongoDB shell version: 3.0.2
connecting to: myDB
DBQuery: myDB.myUserDocColl -> { "_id" : ObjectId("55fd20104ead737a83540a91") }
1
  • Can you paste the output of manogshell here ? Commented Oct 9, 2015 at 9:16

1 Answer 1

1

There are differences between interactive and scripted mode for the shell.

When you run JavaScript in the shell the cursor returned by a find() query is automatically iterated:

The db.collection.find() method returns a cursor. To access the documents, you need to iterate the cursor. However, in the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents in the results.

If you run the same JavaScript in scripted mode (i.e. passing via command line options like --eval), you need to explicitly iterate the cursor and print the results using print() or printjson():

mongo myDB --quiet --eval 'printjson(db.myUserDocColl.find({"_id" : ObjectId("55fd20104ead737a83540a91")},{name:1,email:1,mobileNumber:1,"_id":0}).toArray())'

I also added the --quiet option to the this example command line, which removes extra output that often isn't wanted for a script (eg. the shell version header and "connecting to..." message).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.