Skip to main content
 首页 » 编程设计

c#之在所有集合中查找字段的最大值

2024年02月05日28xxx_UU

我有一个包含集合的数据库,这些集合包含表单上的文档:

{ "_id" : 4, "value" : 2 } 

我想以一种有效的方式在所有集合中找到最大的 "_id"。目前,我有一个工作方法:

public long getLastTimestamp() 
{ 
    var tempList = getChannelNames(); 
    var channelList = new List<IMongoCollection<BsonDocument>>(); 
    var docuList = new List<BsonDocument>(); 
 
    foreach (var channel in tempList) 
    { 
        channelList.Add(_database.GetCollection<BsonDocument>(channel.name)); 
    } 
 
    foreach (var channel in channelList) 
    { 
        var filter = Builders<BsonDocument>.Filter.Exists("_id"); 
        var result = channel.FindAsync(filter).Result.ToList(); 
 
        foreach (var docu in result) 
        { 
            docuList.Add(docu); 
        } 
    } 
 
    var timeList = new List<long>(); 
 
    foreach (var docu in docuList) 
    { 
        Console.WriteLine(docu); 
        if (!docu["_id"].IsObjectId) 
            timeList.Add(docu["_id"].ToInt64()); 
    } 
 
    return timeList.Max(); 
} 

它有效,但我认为它不是很有效率。 有没有人有一些意见或建议?

编辑: 我最终这样做了:

    public long getLastTimestamp() 
    { 
        var filter = Builders<BsonDocument>.Filter.Exists("value"); 
        return getChannelNames() 
            .Select(channel => _database.GetCollection<BsonDocument>(channel.name)) 
            .SelectMany(channel => channel.FindAsync(filter).Result.ToList()) 
            .Max(docu => docu["_id"].ToInt64()); 
    } 

请您参考如下方法:

检查一下:

public long getLastTimestamp() 
{ 
    //var tempList = getChannelNames(); 
    var channelList = new List<IMongoCollection<BsonDocument>>(); 
    var docuList = new List<BsonDocument>(); 
 
    foreach (var channel in getChannelNames()) 
    { 
        var filter = Builders<BsonDocument>.Filter.Exists("_id"); 
        var result = _database.GetCollection<BsonDocument>(channel.name) 
                     .FindAsync(filter).Result.ToList(); 
 
        return result.Where(x => !x["_id"].IsObjectId) 
               .Max(entry => entry["_id"].ToInt64); 
    } 
 
    return 0; 
} 

无法测试它,因为我无法使用这些对象。在 linq 部分,您可能必须转换为列表或数组才能获得可用的 Where() 和 Max()。

再次存储和迭代总是比较慢。

public long getLastTimestamp() 
{ 
    var filter = Builders<BsonDocument>.Filter.Exists("_id"); 
 
    return getChannelNames() 
    .Select(channel => _database.GetCollection<BsonDocument>(channel.name).FindAsync(filter).Result.ToList()) 
    .Where(doc => !doc["_id"].IsObjectId) 
    .Max(doc => doc["_id"].ToInt64); 
}