MongoDB:如何在更新之前对查询进行排序 [英] MongoDB: How to Sort a Query Before Updating

查看:102
本文介绍了MongoDB:如何在更新之前对查询进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个在后端使用MongoDB的Meteor(Node.js)应用程序.在代码的特定位置,我需要更新集合中的 specific 文档.我需要使用Mongo的update()方法,但是在传递正确的(复杂的)查询以缩小到那个特定的文档时遇到了麻烦.我要更新的文档是:

I'm writing a Meteor (Node.js) app which uses MongoDB on the backend. At a certain point in my code, I need to update a specific document within a collection. I need to use Mongo's update() method, but I'm having trouble passing in the proper (complex) query to narrow down to that one, specific document. The document I'm trying to update is:

db.collection.find({market: 'AAA'}).sort({creationDate:-1}).limit(1)

换句话说,collection中的一个文档,其市场是AAA,并且是最近创建的(creationDate是UNIX时间戳号,例如1408829429914).有多个市场为AAA的文档,因此我正在使用sort()和limit(1)来查找最近创建的文档.

In words, the one document in collection that has a market of AAA and was created most recently (creationDate is a UNIX timestamp number, e.g. 1408829429914). There are multiple documents with a market of AAA, so I am using sort() and limit(1) to find the document which was created most recently.

Mongo的 update()似乎没有在更新过程之前,接受排序参数作为查询的一部分.我该怎么做才能缩小文档范围并进行更新?谢谢!

Mongo's update() doesn't seem to accept sorting parameters as part of the query before the update process. What can I do to narrow down to this document and update it? Thanks!

推荐答案

您将需要获取所需的文档,然后通过_id对其进行更新.如果您的收藏集名为Markets,则代码如下所示:

You will need to fetch the document you want and then update it by _id. If your collection was called Markets, the code would look like:

var market = Markets.findOne({market: 'AAA'}, {sort: {creationDate:-1}});
Markets.update(market._id, {$set: {fancy: true}});

值得一提的是,即使MongoDB支持您要寻找的优化,流星客户端代码也只能通过_id进行更新.

It's worth mentioning that even if MongoDB supported the optimization you are looking for, meteor client code can only update by _id anyway.

这篇关于MongoDB:如何在更新之前对查询进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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