简体   繁体   English

MongoDB:如何在更新之前对查询进行排序

[英]MongoDB: How to Sort a Query Before Updating

I'm writing a Meteor (Node.js) app which uses MongoDB on the backend. 我正在编写一个在后端使用MongoDB的Meteor(Node.js)应用程序。 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. 我需要使用Mongo的update()方法,但是我无法通过正确的(复杂的)查询来缩小到特定文档的范围。 The document I'm trying to update is: 我想要更新的文件是:

db.collection.find({market: 'AAA'}).sort({creationDate:-1}).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, eg 1408829429914 ). 换言之, collection中具有AAA市场并且最近创建的一个文档(creationDate是UNIX时间戳编号,例如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. 有多个市场为AAA文档,所以我使用sort()和limit(1)来查找最近创建的文档。

Mongo's update() doesn't seem to accept sorting parameters as part of the query before the update process. 在更新过程之前,Mongo的update()似乎不接受排序参数作为查询的一部分。 What can I do to narrow down to this document and update it? 我该怎么做才能缩小到这个文档并进行更新? Thanks! 谢谢!

You will need to fetch the document you want and then update it by _id . 您需要获取所需的文档,然后通过_id更新它。 If your collection was called Markets , the code would look like: 如果您的馆藏名为Markets ,代码如下:

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

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支持您正在寻找的优化,流星客户端代码也只能通过_id更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM