4

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.

1

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

2 Comments

documents.ConvertAll() showing error. IMongoQueryable<BsonDocument> does not contain a definition for 'ConvertAll' and no accessible extension method 'ConvertAll' accepting a first argument of type.....
Try to convert to list first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.