C# 构建Mongodb过滤条件-4

以Eq,ElemMatch为例,假如一个document中有a,b,clist三个字段,clist为一个array类型的document,现在想要查询a=11,b=22并且clist中的riqi为2020-10-2的数据写法

1、强类型写法

FilterDefinition<Test> filterDefinition = filterDefinitionBuilder.And(
                    filterDefinitionBuilder.Eq(r => r.a, 11),
                    filterDefinitionBuilder.Eq(r => r.b, 22),
                    filterDefinitionBuilder.ElemMatch(r => r.clist,
                        r => riqi == '2020-10-2'));

2、非强类型写法

FilterDefinitionBuilder<BsonDocument> filterDefinitionBuilder = new FilterDefinitionBuilder<BsonDocument>();
                FieldDefinition<BsonDocument> fieldDefinition = "clist";
                FilterDefinitionBuilder<BsonDocument> filterDefinitionZiBuilder = new FilterDefinitionBuilder<BsonDocument>();
                FilterDefinition<BsonDocument> filterDefinition = filterDefinitionBuilder.And(
                    filterDefinitionBuilder.Eq("a", 11),
                    filterDefinitionBuilder.Eq("b", 22),
                    filterDefinitionBuilder.ElemMatch(fieldDefinition, filterDefinitionZiBuilder.Eq("riqi", "2020-10-2"))); 
                 

3、也可以直接使用mongo语句

FilterDefinition<BsonDocument> filter = @"{""a"":11,""b"":22,""clist"": { ""$elemMatch"": { ""riqi"": ""2020-10-2""} } }";

 

  

posted @ 2021-01-19 11:14  zhaogaojian  阅读(1642)  评论(0编辑  收藏  举报