MongoDB 4.2中bulkWrite()结果为何缺少modifiedCount字段?
MongoDB 4.2中bulkWrite返回结果缺失modifiedCount的原因及替代方案
问题场景
我使用MongoDB 4.2版本,执行官方文档中的bulkWrite示例脚本:
db.pizzas.insertMany( [ { _id: 0, type: "pepperoni", size: "small", price: 4 }, { _id: 1, type: "cheese", size: "medium", price: 7 }, { _id: 2, type: "vegan", size: "large", price: 8 } ] ) try { db.pizzas.bulkWrite( [ { insertOne: { document: { _id: 3, type: "beef", size: "medium", price: 6 } } }, { insertOne: { document: { _id: 4, type: "sausage", size: "large", price: 10 } } }, { updateOne: { filter: { type: "cheese" }, update: { $set: { price: 8 } } } }, { deleteOne: { filter: { type: "pepperoni"} } }, { replaceOne: { filter: { type: "vegan" }, replacement: { type: "tofu", size: "small", price: 4 } } } ] ) } catch( error ) { print( error ) }
实际返回结果缺失官方文档提及的modifiedCount字段:
{ "acknowledged" : true, "deletedCount" : 1.0, "insertedCount" : 2.0, "matchedCount" : 2.0, "upsertedCount" : 0.0, "insertedIds" : { "0" : 3.0, "1" : 4.0 }, "upsertedIds" : { } }
甚至简化后的单update操作也无法获取该字段:
db.someCollection.insertOne({ "_id": 1, "field": "some-value" }) var result = db.someCollection.bulkWrite([{ updateOne: { filter: { "_id": 1 }, update: { "$set": { "field": "another-value" } }, upsert: false } }]) printjson(result)
返回结果:
{ "acknowledged" : true, "deletedCount" : 0.0, "insertedCount" : 0.0, "matchedCount" : 1.0, "upsertedCount" : 0.0, "insertedIds" : { }, "upsertedIds" : { } }
一、modifiedCount缺失的原因
MongoDB 4.2版本中,bulkWrite默认不会返回modifiedCount字段。这个字段用于统计实际被修改内容的文档数量,默认关闭该统计返回是出于性能优化考虑。要获取该字段,需要在执行bulkWrite时,在第二个参数中显式指定{ getModifiedCount: true }配置:
var result = db.someCollection.bulkWrite( [ { updateOne: { filter: { "_id": 1 }, update: { "$set": { "field": "another-value" } }, upsert: false } } ], { getModifiedCount: true } // 开启返回modifiedCount ) printjson(result)
添加该配置后,返回结果就会包含modifiedCount字段。从MongoDB 4.4版本开始,modifiedCount才会默认出现在bulkWrite的返回结果中。
二、matchedCount能否替代modifiedCount?
两者无法直接等价替代,核心差异在于统计逻辑:
matchedCount:统计被查询条件匹配到的文档数量,无论文档内容是否真的被修改。例如执行$set操作但设置的值与原字段值完全一致时,matchedCount会计数1,但实际没有修改任何内容。modifiedCount:仅统计实际发生内容变更的文档数量,只有当文档内容确实被修改时才会计数。
如果你的业务仅需要确认有多少文档被匹配并执行了更新操作,matchedCount可以满足需求;但如果需要精确统计实际被修改的文档数量,必须开启getModifiedCount参数来获取modifiedCount。
内容的提问来源于stack exchange,提问作者Harindaka
相关产品推荐
相关产品推荐

