无法从查询更新最后一个文档

kka*_*bat 6 mongodb

您好,我是 Mongodb 的新手,我目前正在尝试更新查询结果中的最后一个文档,但这样做时遇到了麻烦。

我知道如何使用

 db.collection.find().sort({$natural:-1}).limit(1)
Run Code Online (Sandbox Code Playgroud)

但我该如何更新呢?我试着做:

 db.collection.update(db.collection.find().sort({$natural:-1}).limit(1))
Run Code Online (Sandbox Code Playgroud)

但这没有用。我不认为:

 db.collection.update(query,update,option).sort({$natural:-1}).limit(1))
Run Code Online (Sandbox Code Playgroud)

会做我想做的。我检查了官方文档,但在仅查询最后一个文档时找不到任何内容。

Joh*_*yHK 8

您可以使用findAndModify执行需要排序以识别要更新的文档的更新:

db.test.findAndModify({
    query: {},
    sort: {$natural: -1},
    update: {$set: {foo: 'bar'}}
})
Run Code Online (Sandbox Code Playgroud)