Search code examples
c#mongodbmongodb-.net-driver

How can i translate this mongodb query to c# driver?


How can i write a compatible c# code for this?

I know i can do projection like this:

var projection = Builders<BsonDocument>.Projection.Include("title");

But no idea how to project the last name to get the author's last name after a lookup aggregation

db.books.aggregate(
   [
      {
         $project: {
            title: 1,
            lastName: "$author.lastName",
         }
      }
   ]
)

Solution

  • Try this one

                var project = new BsonDocument
                {
                    {
                        "$project",
                        new BsonDocument
                        {
                            {"title", 1},
                            {"lastName", "$author.lastName"},
                        }
                    }
                };
    
                var pipelineLast = new[] { project };
    
    
                var resultLast = db.books.Aggregate<BsonDocument>(pipelineLast);
                var matchingExamples = await resultLast.ToListAsync();
                foreach (var example in matchingExamples)
                {
    // Display the result 
                }