MongoDB 使用 c# 获取 collection 中所有键的名称

MongoDB Get names of all keys in collection using c#

如何使用 C# 获取 MongoDB collection 中所有键的名称。 我正在使用 mongocsharpdriver。
我可以使用

获取所有记录

var collection1 = database1.GetCollection("Games").FindAll();

现在我需要 display/use 它的键名。我需要已获取的 collection 键名。 例如如果我有 collection 其中

{ "_id" : ObjectId("c3"), "GameID" : 20, "GameName" : "COD5", "Cost" : 100}
{ "_id" : ObjectId("c4"), "GameID" : 21, "GameName" : "NFS", "Publisher" : "EA"}
{ "_id" : ObjectId("c5"), "GameID" : 22, "GameName" : "CS", "Cost" : 200}

所以我应该得到 GameID、GameName、Cost、Publisher 等键的列表。

我也经历了 MongoDB Get names of all keys in collection 但无法实现它,不理解它并且遇到了 mapreduce 问题。

灵感来自您问题中的 link:

string map = @"function() { 
        for (var key in this) { emit(key, null); }
        }";
string reduce = @"function(key, stuff) { return null; }";
string finalize = @"function(key, value){
            return key;
        }";
MapReduceArgs args = new MapReduceArgs();
args.FinalizeFunction = new BsonJavaScript(finalize);
args.MapFunction = new BsonJavaScript(map);
args.ReduceFunction = new BsonJavaScript(reduce);
var results = collection1.MapReduce(args);
foreach (BsonValue result in results.GetResults().Select(item => item["_id"]))
{
    Console.WriteLine(result.AsString);
}

一个非常低效但简单的方法是

HashSet<string> keys = new HashSet<string>();
foreach (var rover in collection1.FindAll())
{
    rover.Names.ToList().ForEach(p => keys.Add(p));
}

请记住,无论如何实现,查找键集总是必须迭代整个集合,因此在较大的集合上会非常慢。

在较大的集合上使用 Map/Reduce 解决此问题是有意义的,因为这避免了我在上面发布的解决方案引起的所有数据传输和反序列化开销,但您通常应该尽量避免这样做像这样 完全 。至少,不要在需要同步的地方做。

如果您需要以某种方式快速了解所有字段的集合,最好在 写入 期间跟踪字段并将字段列表存储在单独的集合中某处。