Search code examples
c#mongodbblazormongodb-.net-driver.net-8.0

MongoDB .NET Driver - Aliasing fields in the projection


How to add alias in .NET 8 Blazor C# to change the field name?

var project = Builders<BsonDocument>.Projection.Include("NameField").Include("_id")

How can I change the name NameField to just Name?

var client = new MongoClient();
var db = client.GetDatabase("DB");
var coll = db.GetCollection<BsonDocument>("CollectionName");

var filter = Builders<BsonDocument>.Filter.Eq("_id", id);
var query = coll.Find(filter);

How can I use the alias in this code?

Any guidance or suggestions would be greatly appreciated.


Solution

  • You can assign the projection with the BsonDocument instance. It works the same as writing the MongoDB query.

    ProjectionDefinition<BsonDocument> projection = new BsonDocument
    {
        { "_id", 1 },
        { "Name", "$NameField" }
    };
    
    var filter = Builders<BsonDocument>.Filter.Eq("_id", id);
    var query = coll.Find(filter)
        .Project(projection);