0

Using mongodb and am trying to get a specific value from a collection in the db. I am able to get the complete export using

mongoexport --db database --collection name 

But the output is a large file and I am trying to get a specific set of key/pair in it.

ex: "Name": "Value"

there are several names and I just need to print all the names in the collection.

What would be the command syntax from a UNIX shell ?

I looked at this but that is from with in the mongo shell.

thanks

Community
  • 1
  • 1
hypermails
  • 726
  • 1
  • 10
  • 28

3 Answers3

1

To request all fields from collection yourCollection in MyDatabase :

mongo --quiet 127.0.0.1/MyDatabase --eval 'printjson(db.yourCollection.find().toArray());'

To request only fields name field from collection yourCollection in MyDatabase :

mongo --quiet 127.0.0.1/MyDatabase --eval 'printjson(db.yourCollection.find({},{"_id":0,"name":1}).toArray());'
Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
0

You could also have a script to execute and save you the time of manually writing in those commands. Execute something like

mongo localhost:27017/test myfile.js

and in the javascript file input

db.name.findOne()
db.name().find({},{"_id":0,"Name":1}).toArray());

please see https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/ and [How to execute mongo commands through shell scripts?

Community
  • 1
  • 1
glass_chain
  • 13
  • 1
  • 7
0

If your goal is to export documents matching a specific condition from the database, you can pass a query to mongoexport using the -q parameter. For example:

mongoexport -d db -c coll -q '{"Name":"Value"}'

This will export all documents containing the field "Name" having the value "Value".

You can also pass the --quiet parameter to mongoexport if you prefer to have the output without any informative content, such as number of exported documents.

Please see https://docs.mongodb.com/manual/reference/program/mongoexport/ for more information regarding the mongoexport tool.

kevinadi
  • 13,365
  • 3
  • 33
  • 49