我正在使用 MongoDB c# 驱动程序 2.0。我试图在不指定类型或类的情况下获取集合。观察:
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());
}
如您所见,我应该在声明
IMongoCollection
时指定一个类。有没有一种方法可以在不指定a类的情况下使用MongoDB驱动程序?
MongoDb 在泛型参数中支持
dynamic
类型。
IMongoCollection<dynamic> _myCollection = _mongoDb.GetCollection<dynamic>("Collection");
参见 http://mongodb.github.io/mongo-csharp-driver/2.0/what_is_new/#new-api 。下面的例子:
支持动态。
var person = new ExpandoObject(); person.FirstName = "Jane"; person.Age = 12; person.PetNames = new List<dynamic> { "Sherlock", "Watson" }; await db.GetCollection<dynamic>("people").InsertOneAsync(person);