4

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?

Luke101
  • 63,072
  • 85
  • 231
  • 359

1 Answers1

10

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

Ron Beyer
  • 11,003
  • 1
  • 19
  • 37