C#MongoDB使用Builders查找派生对象

c# mongodb find derived object with Builders(C#MongoDB使用Builders查找派生对象)

本文介绍了C#MongoDB使用Builders查找派生对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个集合,它们存储从同一对象继承的两个不同对象(每个对象表示一个对象)。

类似:

public abstract class BaseClass
{
    public string name = "someName";
}

public class FirstClass : BaseClass { ... }
public class SecondClass : BaseClass { ... }

var FirstCollection = mongo.GetCollection<FirstClass>("First");
var SecondClass =    mongo.GetCollection<SecondClass>("Second");

现在,我有一个查询要运行这两个集合,只使用公共字段。 我想使用相同的查询,使用"MongoDB.Driver.Builders"。

类似:

var filter = Builders<BaseClass>.Filter.Where(y => y.name == "someName");
var result = FirstCollection.Find(filter);

您知道怎么做吗?

推荐答案

使用以下设置,您可以执行与已有操作大致相同的操作。这是上下文:

public class Context
{
    public const string DATABASE_NAME = "Test";
    public const string FIRST_COLLECTION_NAME = "FirstCollection";
    public const string SECOND_COLLECTION_NAME = "SecondCollection";

    private static readonly IMongoClient _client;
    private static readonly IMongoDatabase _database;
    static Context()
    {
        var connectionString = ConfigurationManager.AppSettings["MongoDbServer"];
        _client = new MongoClient(connectionString);
        _database = _client.GetDatabase(DATABASE_NAME);
    }

    public IMongoClient Client => _client;

    public IMongoCollection<First> FirstCollection =>
        _database.GetCollection<First>(FIRST_COLLECTION_NAME);

    public IMongoCollection<Second> SecondCollection =>
        _database.GetCollection<Second>(SECOND_COLLECTION_NAME);
}
FirstSecondBase类与您的相同。然后您可以找到您的文档,如下所示:

var context = new Context();
var builder = Builders<First>.Filter;
var filter = builder.Eq(x => x.Name, "Paul");
//You can insert like this:
//context.FirstCollection.InsertOne(new First(){Name = "Paul", Age = 33});
var result = context.FirstCollection.Find(filter).ToList();

更新

编辑后,我能想到的唯一方法是:

var result = context.FirstCollection.Find(x=> x.Name == "Paul").ToList();

这篇关于C#MongoDB使用Builders查找派生对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C#MongoDB使用Builders查找派生对象