6

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?

8
  • 1
    Have you tried using <dynamic> in there? See mongodb.github.io/mongo-csharp-driver/2.0/what_is_new/#new-api Commented Apr 30, 2015 at 1:10
  • You are calling _mongoDb.GetCollection without declaring a class, that should work for you Commented Apr 30, 2015 at 1:27
  • @RonBeyer Let me try that Commented Apr 30, 2015 at 1:36
  • @faljbour It is giving me a syntax error. The commented out code will work. But don't want to specify a class. Commented Apr 30, 2015 at 1:37
  • 1
    @RonBeyer: Care to post that as an answer so the question is officially answered? Upvote promised... Commented Apr 30, 2015 at 7:50

1 Answer 1

11

MongoDb supports a dynamic type in the generic parameter.

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

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

Support for dynamic.

var person = new ExpandoObject(); 
person.FirstName = "Jane";
person.Age = 12; person.PetNames = new List<dynamic> { "Sherlock", "Watson" };
await db.GetCollection<dynamic>("people").InsertOneAsync(person);
Sign up to request clarification or add additional context in comments.

Comments

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.