我正在使用一个集合,其中有数百万条记录以异步方式填充,因此无法保证顺序。
查询MongoDB FindAsync方法时,将允许添加筛选器,但不允许添加排序。
如何确保使用iasynccursor返回的记录的顺序?我的收藏中的纪元日期戳字段有一个升序索引,这足以保证排序顺序吗?.
====================
findasync方法返回一个iasynccursor。记录以任意批返回,这些批使用using/while构造使用以下方法进行处理。

var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = new BsonDocument();
var count = 0;
using (var cursor = await collection.FindAsync(filter))
{
    while (await cursor.MoveNextAsync())
    {
        var batch = cursor.Current;
        foreach (var document in batch)
        {
            // What order will these records be in? how do I guarantee order ascending by epochtimestamp?;
        }
    }
}

每个异步“批处理”是否将根据查询的整体进行排序?如何保证记录的顺序正确?.
epocdatestamp字段上的升序索引将允许我返回一个完整的排序列表(由于记录的数量,需要很长时间)。
我是否应该按照我需要保证的顺序,一次将完整的排序列表重写回数据库?以便将来的iasynccursor查询将按顺序返回记录。
我需要这么做吗?还是升序索引足够了?

最佳答案

排序可以添加到"FindOptions"对象,并作为参数提供给findasync。在本例中,它是对名为epochtimestamp的字段的升序排序。
很简单当你知道怎么做的时候,

    var collection = _database.GetCollection<BsonDocument>("restaurants");
    var filter = new BsonDocument();
    var sort = Builders<BsonDocument>.Sort.Ascending("epochdatestamp");
    var options = new FindOptions<BsonDocument>
                  {
                    Sort = sort
                  };

    var count = 0;
    using (var cursor = await collection.FindAsync(filter, options))
    {
        while (await cursor.MoveNextAsync())
        {
            var batch = cursor.Current;
            foreach (var document in batch)
            {
                // process document
                count++;
            }
        }
    }

09-26 20:26
查看更多