Search code examples
c#mongodbmongodb-.net-drivermongodb-query

How to exclude the _id field while retrieving and displaying data from MongoDB using C#


How do i exclude the _id field from the set of fields returned in C#, there are posts on this website that mention of the .include() and .exclude() methods but those methods are not present in my case.

below is the code where 'secondary' is a field in the outer document which is an array and '.amount' is the field nested within the 'secondary' array ( like a nested document ). Can someone help me out with this please..!

 var fields = "secondary.amount";
        foreach (var document in collection.FindAllAs<BsonDocument>().SetFields(fields))
        {
            foreach (string name in document.Names)
            {
                BsonElement element = document.GetElement(name);                  
                Console.WriteLine("{0}", element.Value);
            }
        }

Solution

  • The Include and Exclude methods are available, they're just not easy to find because they're off in a separate Fields builder class:

    using MongoDB.Driver.Builders; // Make Fields class accessible
    
    var fields = "secondary.amount";
    foreach (var document in collection.FindAllAs<BsonDocument>()
        .SetFields(Fields.Include(fields).Exclude("_id"))
    {
        foreach (string name in document.Names)
        {
            BsonElement element = document.GetElement(name);                  
            Console.WriteLine("{0}", element.Value);
        }
    }