I want to see whether querying with a array element is faster than querying with a key and its value. So I write this to fill my database.
const { MongoClient } = require("mongodb");
const uri = "mongodb://admin:123456@localhost:30001/?retryWrites=true";
const client = new MongoClient(uri);
async function run() {
await client.connect();
const database = client.db("test");
const collection = database.collection("array");
const doc = {
array: [
`${Math.floor(Math.random() * 500)}`,
`${Math.floor(Math.random() * 500)}`,
`${Math.floor(Math.random() * 500)}`,
],
};
let p = Promise.resolve(undefined);
for(i = 0; i < 10000; i++) {
p = p.then(() => collection.insertOne(doc));
}
return p;
}
run().then(()=>{console.log("done")})
setTimeout(() => {
client.close()
}, 120000);
Note that I’m new to programming, so there may be some mistakes and misunderstaindings.
It’s mostly from the example, but after running this I got a promise rejection for E11000 Duplicate Key. I’m not specifying the _id field, so how come? Only one document was inserted correctly. By the way, if I call .then(client.close()) after run(), there will be an MongoTopologyClosedError: Topology is closed. I’m really confused now.