Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MongoDB C# Driver without specifying a class

I am using MongoDB c# driver 2.0. I a trying to get a collection without specifying a type or class. Observe:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core;
using MongoDB.Driver.Linq;
using MongoDB.Shared;

namespace Meshplex.Service.DataWarehouse
{
    public class ProfileControllerMongoDB
    {
        private IMongoDatabase _mongoDb;
        private IMongoCollection _myCollection;
        //private IMongoCollection<ClassHere> _myCollection;

        public ProfileDataControllerMongoDB()
        {
            _mongoDb = GetMongoDatabase();
            _myCollection = _mongoDb.GetCollection(GetCollectionName());
            //_myCollection = _mongoDb.GetCollection<ClassHere>("Collection");
        }

        public async Task<string> GetAllRecords()
        {
            //This should return json
            return await _myCollection.Find(new BsonDocument());
        }

As you see I should be specifying a class when declaring IMongoCollection. Is there a way to use MongoDB Driver without specifying a a class?

like image 826
Luke101 Avatar asked Dec 25 '22 19:12

Luke101


1 Answers

MongoDb supports a dynamic type in the generic parameter.

IMongoCollection<dynamic> _myCollection = _mongoDb.GetCollection<ClassHere>("Collection");

See http://mongodb.github.io/mongo-csharp-driver/2.0/what_is_new/#new-api

like image 148
Ron Beyer Avatar answered Jan 13 '23 19:01

Ron Beyer