使用C#从MongoDB检索和显示数据时如何排除_id字段 [英] How to exclude the _id field while retrieving and displaying data from MongoDB using C#

查看:239
本文介绍了使用C#从MongoDB检索和显示数据时如何排除_id字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何从C#返回的字段集中排除_id字段,此网站上有一些帖子提到.include()和.exclude()方法,但在我的情况下不存在这些方法. /p> 以下是

的代码,其中"secondary"是外部文档中的一个字段,该字段是一个数组,而".amount"是嵌套在"secondary"数组中的字段(如嵌套文档).有人可以帮我这个忙吗..!

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

解决方案

IncludeExclude方法可用,因为它们不在单独的Fields构建器类中而很难找到:

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

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

解决方案

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

这篇关于使用C#从MongoDB检索和显示数据时如何排除_id字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆