'MongoDB BsonDocument - Serialize JSON as key-object
I have a doubt if it is possible to serialize a collection of BsonDocument results as a JSON pair of key objects.
For example, I attach a piece of code that creates 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 shows it gives 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 it as a set of key-object JSON instead of an 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.
Solution 1:[1]
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());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yong Shun |