Mongo搜索查询.net c#

时间:2018-01-23 10:35:37

标签: c# .net mongodb

假设我有以下变量: string SKU,string Purchase,string Slider,string Category

..和" ID" Mongo中的字段必须包含SKU中的字符串值,或者如果其为null或为空,则不适用。 ..字段" URL"在Mongo中必须包含Purchase中的字符串值,或者如果其为null或为空,则不适用。 ..字段"参考"在Mongo中必须包含Slider中的字符串值,或者如果其为null或为空,则不适用。 ..字段"类别"必须在Category中包含字符串值,或者如果其为null或为空,则不适用。

我最终需要计算结果数量。

如何在.net中构建查询?

3 个答案:

答案 0 :(得分:0)

您可以使用FilterDefinition<TDocument>FilterDefinitionBuilder<TDocument>

请参阅:http://mongodb.github.io/mongo-csharp-driver/2.4/reference/driver/definitions/#filters

答案 1 :(得分:0)

创建空过滤器,然后使用逻辑和运算符&=来连接过滤条件(如果a和b和c ...)。

var client = new MongoClient();
var database = client.GetDatabase("MyDatabase");
var collection = database.GetCollection<Record>("MyCollection");

FilterDefinition<Record> filter = Builders<Record>.Filter.Empty;
if(!string.IsNullOrEmpty(skuValue)) filter &= Builders<Record>.Filter.Eq(r => r.ID, skuValue);
if(!string.IsNullOrEmpty(purchaseValue)) filter &= Builders<Record>.Filter.Eq(r => r.URL, purchaseValue);
if(!string.IsNullOrEmpty(sliderValue)) filter &= Builders<Record>.Filter.Eq(r => r.Refer, sliderValue);
if(!string.IsNullOrEmpty(categoryValue)) filter &= Builders<Record>.Filter.Eq(r => r.Category, categoryValue);

要应用过滤器和检索记录,请尝试以下方法:

var documents = collection.Find<Record>(filter).ToList();
foreach (var document in documents)
{
    Console.WriteLine(document.ID);
}

这是我的记录课。

public class Record
{
    [BsonId]    
    public ObjectId _id { get; set; }
    public string ID { get; set;}
    public string URL {get; set;}
    public string Refer {get; set;}
    public string Category { get; set; }
}

答案 2 :(得分:0)

由于您提到字段必须包含个字符串值,因此我假设您要应用.Contains()而不是检查字符串是否相等。 以下内容应该起作用,并且不区分大小写。

使用collection作为您的IMongoCollection<Record>,并像derloopkat的回答中强键入Record

var query = collection.AsQueryable();

if (!string.IsNullOrEmpty(sku))
{
    query = query.Where(r => r.ID.ToLower().Contains(sku));
}

if (!string.IsNullOrEmpty(purchase))
{
    query = query.Where(r => r.URL.ToLower().Contains(purchase));
}

if (!string.IsNullOrEmpty(slider))
{
    query = query.Where(r => r.Refer.ToLower().Contains(slider));
}

if (!string.IsNullOrEmpty(category))
{
    query = query.Where(r => r.Category.ToLower().Contains(category));
}

// Commented out, since you mentioned you only want the count
// var results = query.ToList();

var count = query.Count();

另一种选择,如果您想动态扩展此过滤支持...

public static class MongoExtensions
{
    public static IMongoQueryable<T> Filter<T>(
        this IMongoQueryable<T> query,
        Expression<Func<T, object>> field,
        string searchValue)
    {
        if (string.IsNullOrEmpty(searchValue))
        {
            return query;
        }

        var rx = new BsonRegularExpression(Regex.Escape(searchValue), "i");
        var filter = Builders<T>.Filter.Regex(field, rx);
        return query.Where(_ => filter.Inject());
    }

    public static IMongoQueryable<T> Filter<T>(
        this IMongoQueryable<T> query,
        string field,
        string searchValue)
    {
        if (string.IsNullOrEmpty(searchValue))
        {
            return query;
        }

        var rx = new BsonRegularExpression(Regex.Escape(searchValue), "i");
        var filter = Builders<BsonDocument>.Filter.Regex(field, rx);
        return query.Where(_ => filter.Inject());
    }
}
var query = collection
    .AsQueryable()
    .Filter("ID", sku) // Refer to the field with a string...
    .Filter("URL", purchase)
    .Filter(r => r.Refer, slider) // ... or use a lambda expression
    .Filter(r => r.Category, category);

var count = query.Count();