$ orderby和Sort之间的MongoDB区别 [英] MongoDB difference between $orderby and Sort
问题描述
我想获取最新的文档,该文档显然是单个文档,因此findOne
应该可以正常工作.但是findOne
此处返回插入的第一个文档.因此,我现在有两个选择,或者将$orderBy
与findOne
一起使用,或者将.sort()
函数与.limit()
在find()
I want to fetch the latest document, which obviously is a single document, thus findOne
should work fine. But findOne
here returns the first document inserted. So I have two options now either use $orderBy
with findOne
or use .sort()
function with .limit()
in find()
使用$ orderBy,它看起来像:
Using $orderBy it would look something like:
db.collection.findOne({$query:{},$orderby:{_id:-1}})
并使用排序:
db.collection.find().sort({_id:-1}).limit(1).pretty()
两者都能正常工作,我只是想知道我在这里更喜欢哪个查询?在性能方面,或者两者在内部的工作方式相同,两者之间没有这种差异.
Both work fine, I just wanted to know which query should I prefer here? In terms of performance, or does both of them work the same way internally and there is no such difference between the two.
推荐答案
As of Mongo 3.2, $orderby
is deprecated.
不建议使用$ orderby运算符.改用cursor.sort().
The $orderby operator is deprecated. Use cursor.sort() instead.
不幸的是,findOne()
不支持sort()
方法,因此您需要切换到find()
:
Unfortunately, findOne()
doesn't support the sort()
method, so you'll need to switch to find()
:
db.collection.find({}).sort({'key': -1}).limit(1)
这将返回cursor
,因此您需要从游标中提取第一个结果.
This will return a cursor
, so you'll then need to pull the first result from the cursor.
这篇关于$ orderby和Sort之间的MongoDB区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!