How to use mongodb functions with mongoimport?

75 Views Asked by At

Let's say I want to insert an object that contains date objects using mongoimport from the commandline.

echo "{\"int_key\": 1, \"date_key\": new Date(\"2022-12-27\")}" | mongoimport --host "192.168.60.10" --db example_db --collection example_collection

will not work because the object I am trying to insert is not in the form of a valid JSON. The reason I want to use mongoimport is because there is an array of a large number of objects that I want to persist at one go. If I try to use the mongo command the argument length for --eval is too long. For example,

mongo --host "192.168.60.10" --eval "db=db.getSiblingDB(\"example_db\");db.getCollection(\"example_collection\").insert([{\"int_key\": 1, \"date_key\": new Date(\"2022-12-27\")}])"

but the array inside insert() has a very large number of objects. Can you suggest any workaround to this? I was thinking I could use mongoimport to read all the objects put into an array through stdin or a file. The options for using a json array would not allow the kind of array of objects I insert using the insert() in mongo --eval.

1

There are 1 best solutions below

3
Wernfried Domscheit On

You have to use this

echo "{\"int_key\": 1, \"date_key\": {\"$date\": \"2022-12-27\"}}"

It may require:

echo "{\"int_key\": 1, \"date_key\": {\"\$date\": \"2022-12-27T00:00:00Z\"}}"

For other data types see MongoDB Extended JSON (v2)

I use mongoimport in the same way to insert around 6 billion documents per day, it is very fast and reliable.

Depending on how you use it, mongoimport does not import small amount of documents could be relevant for you.