从集合中检索最后一个文档时如何提高性能

How to improve performance when retrieving the last document from a collection

这是一个声明,其中 Limit()Sort() 之前...

var result Candle
dao.c.Find(bson.M{"symbol": "USD"}).Limit(1).Sort("-time").One(&result);

... 这是一个声明,其中 Limit()Sort() 之后:

var result Candle
dao.c.Find(bson.M{"symbol": "USD"}).Sort("-time").Limit(1).One(&result);

以上语句在性能上有区别吗?

我们可能会回答有关 mgo 软件包和 MongoDB 本身的问题。

mgo

Query.Limit() and Query.Sort() methods just operate on the Query object locally, and once you setup the query, you execute it e.g. with Query.One() or Query.All()。您调用方法来设置它的顺序不会被存储并且无关紧要。

在MongoDB

引用自MongoDB doc: Combine Cursor Methods:

The following statements chain cursor methods limit() and sort():

db.bios.find().sort( { name: 1 } ).limit( 5 )
db.bios.find().limit( 5 ).sort( { name: 1 } )

The two statements are equivalent; i.e. the order in which you chain the limit() and the sort() methods is not significant. Both statements return the first five documents, as determined by the ascending sort order on ‘name’.


所以没有区别,它们是等价的,因此具有相同的性能。