使用FSharp获取有关MongoDB集合的一般信息

时间:2018-08-23 17:05:28

标签: c# mongodb f#

我可以用MongoDB检索F#中所有集合的基本信息吗?

我有一个MongoDB,其中包含450多个集合。我可以使用

访问数据库
open MongoDB.Bson
open MongoDB.Driver
open MongoDB.Driver.Core 
open MongoDB.FSharp
open System.Collections.Generic

let connectionString = "mystring"
let client = new MongoClient(connectionString)
let db = client.GetDatabase(name = "Production")

我曾考虑过尝试获取所有集合,然后遍历每个集合名称,并使用

获取有关每个集合的基本信息。
let collections = db.ListCollections()

db.GetCollection([name of a collection])

但是db.GetCollection([name])要求我定义一个类型以提取有关每个集合的信息。这对我来说是一个挑战,因为我不想为每个集合定义一个类型,而每个集合的类型> 450,坦率地说,我对这个数据库的了解并不多。 (实际上,我的组织中没有人这样做;这就是为什么我要整理一个非常基本的数据字典的原因。)

确定每个集合的类型确实有必要吗?我可以使用MongoCollection methods available here而不必为每个集合定义类型吗?


编辑:最终,我希望能够输出馆藏名称,每个馆藏中的 n 文档,每个馆藏中的字段名称列表,以及每个字段类型的列表。

1 个答案:

答案 0 :(得分:3)

我选择用C#编写示例,因为我对C#驱动程序更加熟悉,它是问题上列出的标记。您可以对每个集合进行汇总,以找到每个文档的所有顶级字段及其(mongodb)类型。

聚合过程分为3个步骤。假设输入的是10个文档,这些文档都具有以下形式:

{
  "_id": ObjectId("myId"),
  "num": 1,
  "str": "Hello, world!"
}
  1. $project将每个文档转换为具有值fieldNamefieldType的文档数组。使用单个数组字段输出10个文档。数组字段将包含3个元素。

  2. $unwind字段信息的数组。输出30个文档,每个文档都有一个与步骤1的输出中的元素相对应的字段。

  3. $group中的fieldNamefieldType字段以获取不同的值。输出3个文件。由于在此示例中,具有相同名称的所有字段始终具有相同的类型,因此每个字段只有一个最终输出文档。如果两个不同的文档定义了相同的字段,一个为字符串,一个为int,则在此结果集中,这两个字段将有单独的条目。


// Define our aggregation steps.
// Step 1, $project:
var project = new BsonDocument
{ {
    "$project", new BsonDocument
    {
        {
            "_id", 0
        },
        {
            "fields", new BsonDocument
            { {
                "$map", new BsonDocument
                {
                    { "input", new BsonDocument { { "$objectToArray", "$$ROOT" } } },
                    { "in", new BsonDocument {
                        { "fieldName", "$$this.k" },
                        { "fieldType", new BsonDocument { { "$type", "$$this.v" } } }
                    } }
                }
            } }
        }
    }
} };

// Step 2, $unwind
var unwind = new BsonDocument
{ {
    "$unwind", "$fields"
} };

// Step 3, $group
var group = new BsonDocument
{
    {
        "$group", new BsonDocument
        {
            {
                "_id", new BsonDocument
                {
                    { "fieldName", "$fields.fieldName" },
                    { "fieldType", "$fields.fieldType" }
                }
            }
        }
    }
};

// Connect to our database
var client = new MongoClient("myConnectionString");
var db = client.GetDatabase("myDatabase");

var collections = db.ListCollections().ToEnumerable();

/*
We will store the results in a dictionary of collections.
Since the same field can have multiple types associated with it the inner value corresponding to each field is `List<string>`.

The outer dictionary keys are collection names. The inner dictionary keys are field names.
The inner dictionary values are the types for the provided inner dictionary's key (field name).
List<string> fieldTypes = allCollectionFieldTypes[collectionName][fieldName]
*/
Dictionary<string, Dictionary<string, List<string>>> allCollectionFieldTypes = new Dictionary<string, Dictionary<string, List<string>>>();

foreach (var collInfo in collections)
{
    var collName = collInfo["name"].AsString;
    var coll = db.GetCollection<BsonDocument>(collName);

    Console.WriteLine("Finding field information for " + collName);                

    var pipeline = PipelineDefinition<BsonDocument, BsonDocument>.Create(project, unwind, group);
    var cursor = coll.Aggregate(pipeline);
    var lst = cursor.ToList();

    allCollectionFieldTypes.Add(collName, new Dictionary<string, List<string>>());
    foreach (var item in lst)
    {
        var innerDict = allCollectionFieldTypes[collName];

        var fieldName = item["_id"]["fieldName"].AsString;
        var fieldType = item["_id"]["fieldType"].AsString;

        if (!innerDict.ContainsKey(fieldName))
        {
            innerDict.Add(fieldName, new List<string>());
        }

        innerDict[fieldName].Add(fieldType);
    }
}

现在,您可以遍历结果集:

foreach(var collKvp in allCollectionFieldTypes)
{
  foreach(var fieldKvp in collKvp.Value)
  {
    foreach(var fieldType in fieldKvp.Value)
    {
      Console.WriteLine($"Collection {collKvp.Key} has field name {fieldKvp.Key} with type {fieldType}");
    }
  }
}
相关问题