MongoDB: How to Sort a Query Before Updating

南笙酒味 提交于 2020-01-04 05:18:14

问题


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)

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'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!


回答1:


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}});

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



来源:https://stackoverflow.com/questions/25467010/mongodb-how-to-sort-a-query-before-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!