C# Project with a filter

Been trying to convert this atlas projection to c# for a while now with now luck. Any insight on how to use a filter in a projection with the c# driver and classes?

[
  {
    $match: {
      _id: ObjectId("647615c2422457db597f9d96")
    }
  },
  {
    $project: {
      accountMembers: {
        $filter: {
          input: "$accountMembers",
          as: "eachItem",
          cond: {
            $eq: ["$$eachItem.createdById", "userId"]
          }
        }
      }
    }
  }
]

In c# this is where I am:

var filterDef = Builders<TAccount>.Filter.Eq(x => x.Id, "647615c2422457db597f9d96");

return await Repository.Aggregate()
            .Match(filterDef)
            .Project(??????);

Hi Jeff! You can accomplish this using the Projection Builder API and a LINQ expression… the code for that would look something like:

        var filterDef = Builders<TAccount>.Filter.Eq(x => x.Id, "647615c2422457db597f9d96");
        var result = repository.Aggregate()
            .Match(filterDef)
            .Project(Builders<BsonDocument>.Projection.Expression(x => new {
                AccountMembers = x["accountMembers"].AsBsonArray.Where(y => y["createdById"].AsString == "userId")
            }))
            .ToList();

You can also pass in the expression as a BSON document, which will closely resemble the MQL you’ve written above. This article and video will give you a good idea of some how to proceed there. Note that the article demos both the fluent api as well as a more MQL-oriented workflow.

Thanks again. That put me in the right dirrection. Here is where I ended up:

.Project(Builders<TAccount>.Projection.Expression(
                account => account.Members.Where(member => member.CreatedById == identity.UserId)))
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.