Daniele Armanasco Daniele Armanasco -4 years ago 136
C# Question

Map projection result with mongodb C# driver

I need to map to a simplified document some documents in a collection.
I can obtain what I need with this in the mongo shell:

{ "$project": {
"Team": "$TeamId",
"Marker": "$Properties.marker.Value"

I need to obtain the same result with C# driver (version 2.3.0); I tried this

var aggregation = m_database.GetCollection<BsonDocument>("items").Aggregate();
var projectionDefinition = new BsonDocument("$project", new BsonDocument
{ "Team", "$TeamId"},
{ "Marker", "$Properties.marker.Value" }

var query = aggregation.Project(projectionDefinition);
var result = await query.ToListAsync();

but I get the following error

Command aggregate failed: $expressions are not allowed at the top-level of $project

Someone kwons what's going on?

Answer Source

if you call Project you do have already $project in your bson, so you just simplify your projectionDefinition:

var projectionDefinition = new BsonDocument
            { "Team", "$TeamId"},
            { "Marker", "$Properties.marker.Value" }

My personal opinion: I would avoid using pure bson, MongoDB driver gives you possibilities to use your c# dto classes for it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download