findOne 可以先匹配还是最后匹配? [英] Can findOne match first or last?

查看:69
本文介绍了findOne 可以先匹配还是最后匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我专门使用猫鼬,尽管我认为这并不重要.例如,假设我有一个名为 MongoQueue 的集合,我将一些人添加到该队列中.

I'm specifically using mongoose, although I don't believe that matters that much. For example, say I have a collection called MongoQueue and I add a few people to that queue.

`MongoQueue.save {function(err, firstPerson) {
   if (err) console.log(err);
   MongoQueue.save {function(err, secondPerson) {
      if (err) console.log(err);
      MongoQueue.save {function(err, thirdPerson) {
         if (err) console.log(err);
}}}`


如何检索第一个保存到 MongoQueue 的人?或者....mongoDB 的 findOne() 方法如何缩小搜索范围?我可以指定 findOne() 的行为来选择集合中最旧的文档吗?或者我必须对集合进行排序(这将是最后的手段),如果是这样,我将如何按时间戳排序?

How do I retrieve the person who was first saved to MongoQueue? Or....how does the findOne() method of mongoDB narrow down it's search? Can I specify behavior of findOne() to choose the oldest document in the collection? Or must I do a sort on the collection (this would be last resort), and if so how would I sort by timestamp?

推荐答案

findOne() 函数返回 自然顺序,即磁盘上的顺序.您不能指望这会返回最近最少插入的文档.要返回最近最少插入的文档,您可以使用 find() 函数对 _id 进行逆排序,限制为 1,假设 _id 是为您生成的默认 ObjectId,或者在时间戳上(_id 部分构建,来自时间戳,这就是它与 _id 一起使用的原因).如果你使用_id(它总是被索引)或者索引时间戳字段,这会非常快.

The findOne() function returns documents in the natural order, which is the order on disk. You cannot count on this returning the least recently inserted document. To return the least recently inserted document, you can use the find() function with an inverse sort on _id and a limit of 1, assuming _id is a default ObjectId generated for you, or on a timestamp (_id is built, in part, from a timestamp, which is why it works with _id). If you use _id (which is always indexed) or index the timestamp field, this will be very fast.

这篇关于findOne 可以先匹配还是最后匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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