【问题标题】:Mongodb c# filter using and or operatorMongodb c#过滤器使用和或运算符
【发布时间】:2018-04-12 16:25:08
【问题描述】:

我在mongodb中有json文件

示例

{
 "SchemaName": "Intelligence",
 "SchemaDescription": "WindPower",
 "SchemaType": "WindPower",
 "SchemaTypeId": 1,
 "SchemaData": {
  "ProjectId": 1,
  "LastUpdated": "2016-07-02T19:27:28.000+0000",
  "ProjectName": "Zhonghuashan II",
  "Capacity": 49.0,
  "Technology": "Onshore",
   "Country":{
          "CountryId":1,
          "CountryName":"UnitedKingdom",
          "CountryCode":"UK"
    }
 }
}

现在我正在根据搜索条件过滤数据

var filter = Builders<Schema>.Filter.Or(
                Builders<Schema>.Filter.Where(p => p.SchemaData.ProjectName.ToLower().Contains(searchCriteria.ProjectName.ToLower())),
                Builders<Schema>.Filter.Where(p => p.SchemaData.Technology.ToLower().Contains(searchCriteria.Technology.ToLower())),
                Builders<Schema>.Filter.Where(p => p.SchemaData.Country.CountryName.ToLower().Contains(searchCriteria.Country.ToLower()))
            );
            var list = await collectionHandler.ReadOnly<Schema>().FindSync(filter).ToListAsync();
            return list;

我需要添加条件

  1. searchCriteria.ProjectName ="" || searchCriteria.Technology="" || searchCriteria.Country = "" = return all records

  2. searchCriteria.ProjectName ="abc" and searchCriteria.Technology="xyz" || searchCriteria.Country = "" = return matched records

  3. searchCriteria.ProjectName ="abc" and searchCriteria.Technology="xyz" and searchCriteria.Country = "pqr" = return matched records

  4. searchCriteria.ProjectName ="" || searchCriteria.Technology="xyz" and searchCriteria.Country = "pqr" = return matched records

  5. searchCriteria.Technology="" ="abc" || searchCriteria.Technology="xyz" and searchCriteria.Country = "pqr" = return matched records

说搜索条件的任何属性都可以与搜索条件的其他属性结合使用 and 和 or

【问题讨论】:

    标签: c# asp.net-mvc mongodb linq filter


    【解决方案1】:

    对我来说,我很乐意直接将过滤器作为字符串传递:

        FilterDefinition<BsonDocument> filter = @"{ ""Prop"": { $Or: [{ $and: [...] },{ $and: [...] }] } }";
        var lst = collection.Find(filter);
    

    您可以查看文档:
    https://docs.mongodb.com/v3.2/reference/operator/query/or/

    【讨论】:

      【解决方案2】:

      我是这样做的:

      将此答案作为here的基础

              var idFilter = new BsonDocument { { "_id", new BsonDocument { { "$regex", codeRegex }, { "$options", "i" } } } };
              var nameFilter = new BsonDocument { { "Name", new BsonDocument { { "$regex", codeRegex }, { "$options", "i" } } } };
      
              var filter = new BsonDocument("$or", new BsonArray { idFilter, nameFilter });
      
              var query = _collection.Find(filter)                
                  .SortBy(c=>c.Id);
              return query.ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-09
        • 1970-01-01
        • 1970-01-01
        • 2016-01-12
        • 1970-01-01
        • 2017-07-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多