一说更新命令大家肯定都能想到 update,但在mongoDB 的更新命令中 update 之外,还有 updateOne,updateMany(), findOneAndUpdate(), findAndModify(),有种他大舅他二舅都是他舅的感觉。 那我更新的时候到底用哪个?他几个都有哪些不同?接下来那我们就来看一看。
update
db.collection.update(filter, update[, options])
- fitler,需要更新数据的过滤条件,和 find 一样
- update,需要更新的数据或者更新操作符
inc 等,如果不写操作时,把查询的数据都覆盖成传入的数据
- options 可选配置 upsert,默认 false,如果为true没查询到时增加一条数据。 multi,默认false,只更新第一条数据,如果为 true,更新所有查询到的数据 writeConcern,抛出异常的级别 .... 不常用暂时不提
返回结果不会返回数据,而是一个更新的统计结果:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
// nMatched 匹配到的数量
// nUpserted 新增的数量
// nModified 更新的数量
updateOne
db.collection.updateOne(filter, update, options)
- filter,(同update命令)
- update,必须传入update操作符
- options,可选配置 upsert,(同update命令)
返回结果:
{
"acknowledged": true,
"matchedCount": 1,
"modifiedCount": 1
}
findOneAndUpdate
db.collection.findOneAndUpdate(filter, update, options)
- filter,(同update命令)
- update,(同updateOne命令)
- options, 可选配置 upsert, 同上 sort,排序(1为正序,-1为倒序) returnNewDocument,默认 false,返回原始数据,如果为 true 则返回修改之后的数据。 projection,
返回结果与上边的 update 不同,会返回查询到的第一条数据,类似 findOne
findAndModify
db.collection.findAndModify({
query: <document>,
sort: <document>,
remove: <boolean>,
update: <document or aggregation pipeline>, // Changed in MongoDB 4.2
new: <boolean>,
fields: <document>,
upsert: <boolean>,
bypassDocumentValidation: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
});
findAndModify 更强调操作的原子性,对于操作查询以及执行其它需要取值和赋值风格的原子性操作是十分方便的,使用它可以实现一些简单的类事务操作。应该会比 update 慢一些。