I need to insert a 181 KB json file into a mongo collection, the restriction is that it needs to be done using mongosh.
json_file_path=/some/path/file.json
json_file_string=$(cat $json_file_path)
/mongo/path/monhosh $databaseName
--tlsCertificateKeyFile someAuthDetails
--tlsCAFile someMoreAuthDetails
--quiet
--eval "db.test_collection.insertOne(${json_file_string})"
this seems to be working for smaller files, but with 181 KB, which is not that big, it fails as follows:
-ksh: /mongo/path/monhosh: cannot execute [Arguments list too long]
ive increased ulimit -s from 8000 to 65000, which seems to be the maximum with no luck. any ideas ?
2
Answers
I’d consider using mongorestore, https://www.mongodb.com/docs/database-tools/mongorestore/
Or you can install mongodb compass and manually import the json file into the collection
You have correctly identified the issue: the size of the data exceeds what can be passed in as arguments/params/data to any script or program. What you’re doing is loading the whole file’s data into a shell variable and expanding that in eval.
Instead, that can be built as a script, since you are restricted to only using shell commands &
mongosh
. And that script.js
file will be passed tomongosh
using the--file
param. Since the file will be read directly and doesn’t need the contents to be passed as a param, the file can get as big as it needs to be.Example contents of
my_file.json
withcat my_file.json
:1. Select the DB you want to use:
>
so that it creates a newtemp.js
file2. Add an
insertOne
statement:>>
so that it appends to thetemp.js
file3. Put the contents of your json file into
temp.js
:4. Add the closing parens and semicolon after that:
5. [Optional] Check the file with
cat temp.js
:6. Execute
temp.js
it with the--file
option tomongosh
:In your case, that would be:
If you want to insert many existing documents from
.json
files like this, then repeat steps 2, 3, 4 before finally doing step 6. Or create separate .js scripts to execute withmongosh --file some_file.js
.