Exporting specific documents from MongoDB

Mongodb

MongoDB comes with a useful tool, mongoexport, for exporting collections. However, you can also use it to export specific documents by utilising the query parameter. You can export a single document using it’s ObjectId using a command similar to the following:

mongoexport -h "host_name" -u "username" -d "database_name" -c "collection_name" -q '{"_id":ObjectId("4f045677a1ef264746000011")}' -o output.js -p
  • Replace host_name, username, database_name and collection_name with the appropriate values.
  • Replace 4f045677a1ef264746000011 with the ObjectID that you wish to export

You will be prompted for a password, and then the document will be written to output.js.

To export multiple documents, you can utilise an $in clause in the query parameter like this:

-q '{"_id":{"$in" :[ ObjectId("4f048dc6a1ef26da4b000008"),ObjectId("4ed8ee16a1ef26085600001a"),ObjectId("4efc46e0a1ef26b73d0007be")]}}'

To import these exported documents into another MongoDB server, you can use the mongoimport like so:

mongoimport -h "host_name" -u "username" -p -d "database_name" -c "collection_name" output.js

Glen Scott

I’m a freelance software developer with 18 years’ professional experience in web development. I specialise in creating tailor-made, web-based systems that can help your business run like clockwork. I am the Managing Director of Yellow Square Development.

More Posts

Follow Me:
TwitterFacebookLinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.