Not sure if the answer is just too old, or there are different ways to do it.
Well theoretically the answer specifies a '.js' file but tells about "can do it with shell script".
Anyways, I guess could be that now there is better documentation, but here another way to do it
How to store those commands in mongodb script?
I think the question is also really "Which file type/extension should be use to create mongo script files"
Using Javascript (no need any type of library just mongosh)
Example
db = connect( 'mongodb://localhost/sandbox' );
console.log(db);
console.log(Object.keys(db));
How can we do that in mongodb?
From the mongosh
shell use the load
command with an absolute or relative path to the script.
Example
Assuming we are using linux do the following
mkdir mongo_sandbox
cd mongo_sandbox
touch mongo_script.js
Now let's create a mongo Javascript script, you know use vim, VSCode, pen and paper.. whatever
db = connect( 'mongodb://localhost/myDatabase' );
db.movies.insertMany( [
{
title: 'Titanic',
year: 1997,
genres: [ 'Drama', 'Romance' ]
},
{
title: 'Spirited Away',
year: 2001,
genres: [ 'Animation', 'Adventure', 'Family' ]
},
{
title: 'Casablanca',
genres: [ 'Drama', 'Romance', 'War' ]
}
] )
let movies = db.movies.find();
console.log(movies);
Cool now, lunch mongosh
mongosh sandbox
# ...bla bla bla
sandbox>
Run the script
load( "./mongo_script.js" )
Which outputs
sandbox> load( "./mongo_script.js" )
[
{
_id: ObjectId("64e8560e2932f758ce7d11a3"),
title: 'Titanic',
year: 1997,
genres: [ 'Drama', 'Romance' ]
},
{
_id: ObjectId("64e8560e2932f758ce7d11a4"),
title: 'Spirited Away',
year: 2001,
genres: [ 'Animation', 'Adventure', 'Family' ]
},
{
_id: ObjectId("64e8560e2932f758ce7d11a5"),
title: 'Casablanca',
genres: [ 'Drama', 'Romance', 'War' ]
}
]
true
Documentation