Test code:
const { MongoClient, BSONType } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
const dbName = 'datatest';
async function main() {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('documents');
async function test() {
console.time('operation')
const bulk = collection.initializeUnorderedBulkOp();
for (let i = 0; i < 5000; i++) {
bulk.find({ id: i }).upsert().updateOne({
$set: {
id: i,
test: Math.random().toString()
}
});
}
await bulk.execute();
console.timeEnd('operation')
}
await collection.dropIndex("test");
await collection.createIndex({ id: 1 }, {
name: "test",
unique: true,
partialFilterExpression: {
id: {
$type: [BSONType.int, BSONType.long],
}
}
})
await test()
await collection.dropIndex("test");
await collection.createIndex({ id: 1 }, {
name: "test",
unique: true
})
await test()
}
main()
Log:
operation: 9.031s
operation: 738.926ms