Home > Software engineering >  c# MongoDB BsonDocument - Serialize to json as key-object
c# MongoDB BsonDocument - Serialize to json as key-object

Time:11-12

I have a doubt if is possible to serialize a collection of BsonDocument result as a json pair of key-objects.

For example I attach a piece of code that create a collection of BsonDocument with and _id and name as fields,

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());
        }
    }
}

List 1.1

The piece from the list 1.1 shown, it gives an output as a json array-of-objects,

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

Having the field '_id' as the key of the collection, I would like to serialize as a set of key-object json instead of array-of-objects. The result of serialized json should be like this,

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

I don't know whether is this possible or not

CodePudding user response:

You can convert BsonDocument to Dictionary via System.Linq.

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

  • Related