Skip to content

Instantly share code, notes, and snippets.

@samlaf
Created March 26, 2022 02:45
Show Gist options
  • Save samlaf/c981ab8da5f543b42f3ef7486d817bea to your computer and use it in GitHub Desktop.
Save samlaf/c981ab8da5f543b42f3ef7486d817bea to your computer and use it in GitHub Desktop.
mongodb vs filedb
import fs from "fs";
const n = 5000000;
const s = [];
for (let i = 0; i < n; i++) {
s.push({
idx: i,
});
}
const beforeWrite = Date.now();
fs.writeFileSync("data.json", JSON.stringify(s));
const afterWrite = Date.now();
const b = fs.readFileSync("data.json");
const afterRead = Date.now();
const writeTime = afterWrite - beforeWrite;
const readTime = afterRead - afterWrite;
console.log(
`Writing/Reading ${n} objects to filedb took ${writeTime}/${readTime} ms`
);
import { MongoClient } from "mongodb";
// TODO: use mongoose
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db("scratch");
const scratch = database.collection("scratch");
await scratch.deleteMany({});
const n = 5000000;
const s = [];
for (let i = 0; i < n; i++) {
s.push({
idx: i,
});
}
const beforeWrite = Date.now();
const result = await scratch.insertMany(s);
const afterWrite = Date.now();
const cursor = scratch.find({});
await cursor.forEach(() => {});
const afterRead = Date.now();
const writeTime = afterWrite - beforeWrite;
const readTime = afterRead - afterWrite;
console.log(
`Writing/Reading ${n} objects to filedb took ${writeTime}/${readTime} ms`
);
} finally {
await client.close();
}
}
run().catch(console.dir);
@samlaf
Copy link
Author

samlaf commented Mar 26, 2022

Results:
Writing/Reading 5000000 objects to filedb took 846/26 ms
Writing/Reading 5000000 objects to mongodb took 24082/8239 ms

Of course mongodb can retrieve a document in O(1) though, whereas filedb takes O(n)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment