我有一个包含集合的数据库,这些集合包含表单上的文档:
{ "_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());
}
答案 0 :(得分:2)
检查出来:
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-part上你可能需要转换为list或array才能获得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);
}
答案 1 :(得分:2)
这样的东西?
var filter = Builders<BsonDocument>.Filter.Exists("_id");
getChannelNames()
.SelectMany(channel => _database.GetCollection<BsonDocument>(channel.name))
.SelectMany(channel => channel.FindAsync(filter).Result.ToList()) // Even better w/o ToList
.Where(docu => !docu["_id"].IsObjectId)
.Max(docu => docu["_id"].ToInt64());