[英]Mongodb c# filter using and or operator
I have json documents in mongodb
我在
mongodb
有 json 文件
Sample样本
{
"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"
}
}
}
Now I am filtering data on basis on search criteria现在我正在根据搜索条件过滤数据
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;
I need to add condition我需要添加条件
searchCriteria.ProjectName ="" || searchCriteria.Technology="" || searchCriteria.Country = "" = return all records
searchCriteria.ProjectName ="abc" and searchCriteria.Technology="xyz" || searchCriteria.Country = "" = return matched records
searchCriteria.ProjectName ="abc" and searchCriteria.Technology="xyz" and searchCriteria.Country = "pqr" = return matched records
searchCriteria.ProjectName ="" || searchCriteria.Technology="xyz" and searchCriteria.Country = "pqr" = return matched records
searchCriteria.Technology="" ="abc" || searchCriteria.Technology="xyz" and searchCriteria.Country = "pqr" = return matched records
say any property of search criteria can have combination of and and or with other property of search criteria说搜索条件的任何属性都可以与和或与搜索条件的其他属性组合
For me I'm comfortable with directly passing filters as string:对我来说,我很乐意直接将过滤器作为字符串传递:
FilterDefinition<BsonDocument> filter = @"{ ""Prop"": { $Or: [{ $and: [...] },{ $and: [...] }] } }";
var lst = collection.Find(filter);
You can review the documentation:您可以查看文档:
https://docs.mongodb.com/v3.2/reference/operator/query/or/ https://docs.mongodb.com/v3.2/reference/operator/query/or/
I did it this way:我是这样做的:
Took as base this answer over 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.