c# - 如何在不指定类的情况下使用 MongoDB C# 驱动程序

标签 c# mongodb mongodb-csharp-2.0

我正在使用 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 时指定一个类。有没有一种方法可以在不指定类的情况下使用 MongoDB 驱动程序?

最佳答案

MongoDb 支持 dynamic输入通用参数。

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

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

关于c# - 如何在不指定类的情况下使用 MongoDB C# 驱动程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29957313/

相关文章:

MongoDB 服务器无法启动

c# - 在 C# 中使用 MongoClientSettings 初始化 MongoClient

创建位图时 C# 内存不足

c# - Visual Studio 2008 Extension 快速测试功能? C#

mysql - 测验分层数据的数据库结构?

C# 驱动程序 - LINQ - 聚合 - 包含在 Int[] 中

c# - 使用 .NET 驱动程序 2.0 在 MongoDB 中构建索引

c# - 在转换为 unsigned int 32 时,这在 c# 中意味着什么

c# - 包括 IDN 字符的域名正则表达式 c#

exception - 无法通过 mongodb.conf 更改 mongodb 中的 dbpath