Blacksad
Blacksad

Reputation: 15432

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.

Upvotes: 13

Views: 16330

Answers (6)

Alex Nolasco
Alex Nolasco

Reputation: 19456

for mongoexport version: r4.2.3

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

and for a nested field

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

Upvotes: 5

andydoe
andydoe

Reputation: 224

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.

Upvotes: 0

umbersar
umbersar

Reputation: 1931

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"}'

Upvotes: 0

Eddy
Eddy

Reputation: 3723

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(")!

Upvotes: 3

Harikrushna Adiecha
Harikrushna Adiecha

Reputation: 41

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

Upvotes: 4

dcrosta
dcrosta

Reputation: 26258

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)

Upvotes: 19

Related Questions