I have a js file with the following MongoDB commands:
use sdmforms;
db["formResult"].find({"_id": {$regex: /16235195_5.00/}});
db["formResult"].find({"_id": {$regex: /16238178_5.00/}});
It's just a sample, but the idea is to sequentially run those commands & save the output into a file.
When I run the individual commands in mongosh, they run & I get the on-screen feedback, however, when I try to run the following in Powershell, the files come out empty (0 KB).
mongosh "mongodb://{my_server}/" "C:/Users/my_user/script_directory/MyFile.js" "C:/Users/my_user/output_directory/MyOutputFile.js"
As well, when I run the following command, I get no feedback in Powershell:
mongosh "mongodb://{my_server}/" "C:/Users/my_user/script_directory/MyFile.js"
The file is generated in the folder, but it contains nothing.
How can I create the output file? I don't really care about the format, I just want it as a backup.
I had a similar case, and I was able to get it working by using printjson()
along with .toArray()
inside the script.
Here’s an example of what worked for me. My script.js
use('qe-test');
printjson(db.getCollection('test').find({test: {$ne: null}}).toArray());
And then I ran the script like this in PowerShell to save the output:
mongosh "mongodb://localhost/?directConnection=true" "script.js" > "result.txt"
This way, the query results were printed and saved correctly to the results.txt file:
[
{
_id: ObjectId('6852efda34b4098f9992ab68'),
test: 'my test'
},
{
_id: ObjectId('6852efdd4129c7f4913d4ace'),
test: 'my test 2'
},
{
_id: ObjectId('6852efe07690164e4dc273db'),
test: 'my test 3'
}
]