Include the _ids of existing documents in BulkWriteResult when performing upserts
When performing a bulk operation, it is possible to obtain the _ids of upserted documents via BulkWriteResult. For example:
db.getCollection("test").find({})
db.test.drop()
var bulk = db.test.initializeUnorderedBulkOp();
bulk.find({name: "huey"}).upsert().updateOne({name: "huey"});
bulk.execute();
```
The BulkWriteResult contains the upserted _id:
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 1,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [
{
"index" : 0,
"_id" : ObjectId("5ec77b5cc4a955ce03a4cd2e")
}
]
})
However, when a document already exist, the _id is not returned:
db.test.find()
var bulk = db.test.initializeUnorderedBulkOp();
bulk.find({name: "huey"}).upsert().updateOne({name: "huey", outfit: "red"});
bulk.find({name: "luey"}).upsert().updateOne({name: "luey", outfit: "green"});
bulk.find({name: "duey"}).upsert().updateOne({name: "duey", outfit: "blue"});
bulk.execute();
Returns:
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 2,
"nMatched" : 1,
"nModified" : 1,
"nRemoved" : 0,
"upserted" : [
{
"index" : 1,
"id" : ObjectId("5ec77b5cc4a955ce03a4cd39")
},
{
"index" : 2,
"id" : ObjectId("5ec77b5cc4a955ce03a4cd3a")
}
]
})
This forces you to make a subsequent query to retrieve the entries that weren't upserted.
This request is that BulkWriteResult incorporates a list of matched document ids on a bulk upsertOne operation when it turns out that the documents already exist