Daniele Armanasco
Daniele Armanasco

Reputation: 7451

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:

db.getCollection('items').aggregate([
{ "$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?

Upvotes: 1

Views: 3945

Answers (1)

Maksim Simkin
Maksim Simkin

Reputation: 9679

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.

Upvotes: 4

Related Questions