Export One Object with Mongoexport, How to Specify _Id?

I'm trying to export just one object with mongoexport, filtering by its ID.

I tried:

mongoexport -d "kb_development" -c "articles" -q "{'_id': '4e3ca3bc38c4f10adf000002'}"

and many variations, but it keeps saying

connected to: 127.0.0.1
exported 0 records

(and I'm sure there is such an object in the collection)

In mongo shell I would use ObjectId('4e3ca3bc38c4f10adf000002'), but it does not seem to work in the mongoexport query.

6 Answers

I think you should be able to use ObjectId(...) in the query argument to mongoexport:

mongoexport -d kb_development -c articles -q '{_id: ObjectId("4e3ca3bc38c4f10adf000002")}'

If that does not work, you can use the "strict mode" javascript notation of ObjectIds, as documented here:

mongoexport -d kb_development -c articles -q '{_id: {"$oid": "4e3ca3bc38c4f10adf000002"}}'

(Also note that strict mode JSON is the format produced by mongoexport)

2

You have to specify the _id field by using the ObjectId type. In your question it was specified as a string.

CODE ::

mongoexport -h localhost -d my_database -c sample_collection -q '{key:ObjectId("50584580ff0f089602000155")}' -o my_output_file.json

NOTE :: dont forgot quotes in query

My MongoDB verion: 3.2.4. when I use mongoexport tool in mongo shell:


NOT WORK:

-q '{"_id":ObjectId("5719cd12b1168b9d45136295")}'

-q '{_id: {"$oid": "5719cd12b1168b9d45136295"}}'


WORKs:

-q "{_id:ObjectId('5719cd12b1168b9d45136295')}"

- Though in mongo doc , it says that

You must enclose the query in single quotes (e.g. ') to ensure that it does not interact with your shell environment.


- But, single quote(') does not work! please use double quote(")!

0

for mongoexport version: r4.2.3

mongoexport -q '{"_id": {"$oid": "4e3ca3bc38c4f10adf000002"}}' 

and for a nested field

mongoexport -q '{"_id": {"$oid": "4e3ca3bc38c4f10adf000002"}}' --fields parentField.childField

You do not have to add ObjectId or $oid as suggested by answers above. As has been mentioned by @Blacksad, just get your single and double quotes right.

mongoexport -d kb_development -c articles -q '{_id:"4e3ca3bc38c4f10adf000002"}'

many of the answers provided here didn't work for me, the error was with my double quotes. Here is what worked for me:

mongoexport -h localhost -d database_name -c collection_name -q {_id:ObjectId('50584580ff0f089602066633')} -o output_file.json

remember to use single quote only for the ObjectId string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest