我在insertOne
中同时具有updateOne
和bulkWrite
,如下所示:
async function bulkWrite(users) {
await users.bulkWrite([
{
insertOne: {
document: {
name: 'bulk-insert1',
age: 100
}
},
updateOne: {
filter: {
name: 'mongodb'
},
update: {
$set: {
age: 200
}
}
}
}
])
}
我希望它将插入一个新文档并更新一个现有文档,但是结果有所不同。
我的主要功能:
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";
const DB_NAME = 'javascript-mongodb-bulkwrite-demo';
const COLLECTION_NAME = 'users';
async function run() {
const mongo = await MongoClient.connect(url, {useNewUrlParser: true});
const db = mongo.db(DB_NAME);
await clearDb(db);
const users = await db.createCollection(COLLECTION_NAME);
await createUsers(users);
await printUsers(users);
await bulkWrite(users);
await printUsers(users);
await mongo.close()
}
run();
它使用的其他功能:
async function clearDb(db) {
console.log('------- clearDb --------');
const collections = await db.collections();
await Promise.all(collections.map(async it => {
await it.drop();
}));
}
async function createUsers(users) {
console.log('------- createUsers --------');
users.insertMany([
{
name: 'javascript',
age: 10
}, {
name: 'mongodb',
age: 20
}
])
}
async function printUsers(users) {
console.log('------- printUsers --------');
await users.find().forEach(user => {
console.log(user);
})
}
bulkWrite
函数:async function bulkWrite(users) {
console.log('------- bulkWrite --------');
return await users.bulkWrite([
{
insertOne: {
document: {
name: 'bulk-insert1',
age: 100
}
},
updateOne: {
filter: {
name: 'mongodb'
},
update: {
$set: {
age: 200
}
}
}
}
])
}
当前结果如下:
------- clearDb --------
------- createUsers --------
------- printUsers --------
{ _id: 5c10b6011dd87efa7feb5b47, name: 'javascript', age: 10 }
{ _id: 5c10b6011dd87efa7feb5b48, name: 'mongodb', age: 20 }
------- bulkWrite --------
------- printUsers --------
{ _id: 5c10b6011dd87efa7feb5b47 }
{ _id: 5c10b6011dd87efa7feb5b48, name: 'mongodb', age: 20 }
我希望最后一部分是:
{ _id: 5c10b6011dd87efa7feb5b47, name: 'javascript', age: 10 }
{ _id: 5c10b6011dd87efa7feb5b48, name: 'mongodb', age: 20 }
{ _id: 5c10b6011dd87efa7feb5b49, name: 'bulk-insert1', age: 100 }
我还为此创建了一个演示项目,您可以克隆并运行它:
https://github.com/freewind-demos/javascript-mongodb-bulkwrite-demo
(我将当前代码锁定到
issue
分支) 最佳答案
这只是一个错字。您错过了批量操作之间的一对花括号。
它应该是:
const res = await users.bulkWrite([
{
insertOne: {
document: {
name: 'bulk-insert1',
age: 100
}
}
}, {
updateOne: {
filter: {
name: 'mongodb'
},
update: {
$set: {
age: 200
}
}
}
}
]);