MongoDB with C# - query with dynamically generated predicate

后端 未结 2 1479
南笙
南笙 2021-01-25 05:49

I am having trouble querying a MongoDB database using a predicate which is dynamically generated.

The document structue i am trying to query on is:

{ 
          


        
相关标签:
2条回答
  • 2021-01-25 06:11

    Not sure it's a solution for mongodb, but could you try to use AsExpandable() coming from linqkit (made by the same guy as PredicateBuilder).

    LinqKit (and more info about AsExpandable() and relation with PredicateBuilder) can be found here

    0 讨论(0)
  • 2021-01-25 06:20

    Use the MongoDB Query builder instead of translating the predicate twice:

    using MongoDB.Driver.Builders;
    List<IMongoQuery> queries = new List<IMongoQuery>();
    if (request.CultureId != null && request.CareerId != null) {
      queries.Add(
        Query<Person>.ElemMatch<IDependent>(p => p.Dependents,
          q => Query.And(
            q.EQ(x => x.CareerId, request.CareerId),
            q.EQ(x => x.CultureId, request.CultureId))));
    }
    // ... etc
    // Final Query: 
    var query = Query.And(queries);
    

    I changed the query to use an $elemMatch, because I have the feeling you want to match both careerId and cultureId on the same array element. If that assumption is wrong, adjust the query accordingly.

    0 讨论(0)
提交回复
热议问题