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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With