Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve data in proper JSON format from MongoDB in C#

I want to retrieve all the documents of a collection from mongoDB in C# .Net Web API. Below code is working fine but It is returning BsonDocument

var client = new MongoClient(connectionString);
var db = client.GetDatabase("STRDB");
var mongoCollection = db.GetCollection<BsonDocument>(collection);
var documents = mongoCollection.AsQueryable();
return Ok(documents);

From above code I am getting data in below format (After JSON.stringify() in angular)

[  
   [  
      {  
         "name":"_id",
         "value":"5de9f351baca28556c6a4b71"
      },
      {  
         "name":"Name",
         "value":"Harsha"
      },
      {  
         "name":"Age",
         "value":20
      },
      {  
         "name":"Gender",
         "value":"M"
      },
      {  
         "name":"Skills",
         "value":[  
            {  
               "name":"Java",
               "value":""
            },
            {  
               "name":"Mule",
               "value":true
            },
            {  
               "name":"Angular",
               "value":""
            }
         ]
      }
   ],
   [  
      {  
         "name":"_id",
         "value":"5de9f358baca28556c6a4b72"
      },
      {  
         "name":"Name",
         "value":"Anji"
      },
      {  
         "name":"Age",
         "value":21
      },
      {  
         "name":"Gender",
         "value":"M"
      },
      {  
         "name":"Skills",
         "value":[  
            {  
               "name":"Java",
               "value":""
            },
            {  
               "name":"Mule",
               "value":true
            },
            {  
               "name":"Angular",
               "value":true
            }
         ]
      }
   ]
]

How to receive it in proper JSON format OR how to convert this BSON document in JSON as I am unable to process this output.

like image 470
Abhi Avatar asked Oct 16 '25 14:10

Abhi


1 Answers

Try the following, with conversion.

var client = new MongoClient(connectionString);
var db = client.GetDatabase("STRDB");
var mongoCollection = db.GetCollection<BsonDocument>(collection);
var documents = mongoCollection.AsQueryable();
return Ok(documents.ToList().ConvertAll(BsonTypeMapper.MapToDotNetValue));
like image 97
Athanasios Kataras Avatar answered Oct 18 '25 07:10

Athanasios Kataras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!