MongoDB BsonDocument - 将 JSON 序列化为关键对象

MongoDB BsonDocument - Serialize JSON as key-object

我怀疑是否可以将 BsonDocument 结果集合序列化为 JSON 对关键对象。

例如,我附上了一段代码,它创建了一个 BsonDocument 集合,并将 _id 和名称作为字段,

using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExampleBsonDocumentSerializeToJsonAsArray
{
    class Program
    {
        static void Main(string[] args)
        {
            BsonDocument[] data = new BsonDocument[]{

                new BsonDocument {
                        { "_id" , "1" },
                        { "name" , "name_1" },
                        { "description" , "description_1" },
                }
                ,new BsonDocument {
                        { "_id" , "2" },
                        { "name" , "name_2" },
                        { "description" , "description_2" },
                }
                ,new BsonDocument {
                        { "_id" , "3" },
                        { "name" , "name_3" },
                        { "description" , "description_3" },
                }
            };

            Console.WriteLine(data.ToJson());
        }
    }
}

列表 1.1

列表 1.1 中的片段显示它以 JSON 对象数组的形式给出输出:

[{
    "_id": "1",
    "name": "name_1",
    "description": "description_1"
}, {
    "_id": "2",
    "name": "name_2",
    "description": "description_2"
}, {
    "_id": "3",
    "name": "name_3",
    "description": "description_3"
}]

将字段“_id”作为集合的键,我想将其序列化为一组键对象 JSON 而不是对象数组。序列化后的结果JSON应该是这样的,

{
    "1": {
        "name": "name_1"
      , "description": "description_1"
    },
    "2": {
        "name": "name_2"
      , "description": "description_2"
    },
    "3": {
        "name": "name_3"
      , "description": "description_3"
    }
}

不知道可不可以。

您可以通过 System.LinqBsonDocument 转换为 Dictionary

using System.Linq;
var kvp = data.AsEnumerable()
    .ToDictionary(x => x["_id"], x => new { name = x["name"], description = x["description"] });
        
Console.WriteLine(kvp.ToJson());

Sample program