简体   繁体   中英

MongoDB: How to Sort a Query Before Updating

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, eg 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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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