无法更新查询中的最后一个文档 [英] Trouble updating last document from a query

查看:58
本文介绍了无法更新查询中的最后一个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我是Mongodb的新手,我目前正在尝试更新查询结果中的最后一个文档,但是这样做很麻烦.

Hello I'm new to Mongodb, I am currently trying to update the last document in a query result but having trouble doing so.

我知道如何使用

 db.collection.find().sort({$natural:-1}).limit(1)

但是我该如何更新呢?我尝试这样做:

but how do I update this? I tried doing:

 db.collection.update(db.collection.find().sort({$natural:-1}).limit(1))

但这没用.而且我不认为:

But that didn't work. And I don't think:

 db.collection.update(query,update,option).sort({$natural:-1}).limit(1))

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

would do what i want. I checked the official documentation but couldn't find anything on querying only for the last document.

推荐答案

您可以使用

You can use findAndModify to perform an update that requires sorting to identify the document to update:

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

这篇关于无法更新查询中的最后一个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆