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

﹥>﹥吖頭↗ 提交于 2019-12-12 04:37:49

问题


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);
            }
        }

回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/25995286/how-to-exclude-the-id-field-while-retrieving-and-displaying-data-from-mongodb-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!