Below are two common ways to turn a JSON file into a brand-new collection while you’re on an Ubuntu box that already has MongoDB Community Edition installed.
Pick the one that best fits your workflow:
OPTION A – The “official” way (mongoimport – recommended for > a few hundred docs)
mongoimport is shipped with the MongoDB Database Tools package and is purpose-built for bulk loads.
It runs from the normal Bash prompt, not inside mongosh, but the collection will be visible the moment you reconnect with mongosh.
-
Make sure the tools are installed (Ubuntu ≥ 20.04)
sudo apt-get update
sudo apt-get install -y mongodb-database-tools # gives you mongoimport, mongodump, etc.
-
Put your JSON somewhere readable, e.g. /home/$USER/data/users.json
The file can be either:
• A JSON array … [{ "_id": 1, "name": "Ada" }, { "_id": 2, "name": "Linus" }]
• OR JSON-Lines (one doc per line) …
{ "_id": 1, "name": "Ada" }
{ "_id": 2, "name": "Linus" }
-
Run mongoimport (this will create the database/collection if they don’t exist):
mongoimport \
--uri "mongodb://localhost:27017" \
--db mydb \
--collection users \
--file /home/$USER/data/users.json \
--jsonArray # <-- keep if the file is a single JSON array
# omit --jsonArray if using JSON-Lines
-
Validate in mongosh:
mongosh
> use mydb
> db.users.countDocuments() // should show imported count
> db.users.findOne()
That’s literally it—mongoimport handles batching, _id collisions, etc.
OPTION B – Pure mongosh (handy for quick demos or tiny files)
mongosh has a helper called cat() that lets you read a local file, so you can do everything from inside the shell:
-
Launch mongosh and choose/ create the DB:
mongosh
> use mydb
-
Load the whole JSON file into a JS variable and insert:
(Assumes the file holds a JSON array.)
const docs = JSON.parse(cat('/home/youruser/data/users.json'));
db.users.insertMany(docs); // collection “users” is now created & populated
• If your file is JSON-Lines instead of an array:
cat('/home/youruser/data/users.json')
.split('\n') // break into lines
.filter(Boolean) // drop empty ones
.map(JSON.parse) // string → object
.forEach(doc => db.users.insertOne(doc));
-
Verify:
db.users.countDocuments();
db.users.find().pretty();
Limitations of the pure-mongosh route
• All data lives in memory while inserting; not ideal for GB-scale files.
• No fancy switches for duplicate handling, etc. – you’d code that yourself.
Troubleshooting Tips
• “Unauthorized” errors → make sure the user you connect with has insert privileges on the target DB.
• Large files time out → use mongoimport with --batchSize or --numInsertionWorkers, or temporarily raise net.maxIncomingConnections.
• Validate JSON quickly: jq . /path/file.json (array) or jq -s . file.jsonl >/dev/null (lines).
Choose the path that fits your data size; for anything serious, mongoimport is the go-to tool. Happy importing!