Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 点表示法在C中访问MongoDB查询结果(BsonDocuments)#_C#_.net_Mongodb_Serialization_Mongodb .net Driver - Fatal编程技术网

C# 点表示法在C中访问MongoDB查询结果(BsonDocuments)#

C# 点表示法在C中访问MongoDB查询结果(BsonDocuments)#,c#,.net,mongodb,serialization,mongodb-.net-driver,C#,.net,Mongodb,Serialization,Mongodb .net Driver,如何访问C#中的MongoCursor属性 我有以下代码行: MongoCursor results = collection.Find(searchQuery).SetLimit(10).SetFields( Fields.Include("name1","name", "_id")); MongoDB返回一个数组,每个数组有两个属性:name和name1。在调试器的结果视图中,我可以看到一个数组,数组中的每个项都包含一个MongoDB.Bson.BsonDocument 我想用点表示法访问

如何访问C#中的MongoCursor属性

我有以下代码行:

MongoCursor results = collection.Find(searchQuery).SetLimit(10).SetFields(
Fields.Include("name1","name", "_id"));
MongoDB返回一个数组,每个数组有两个属性:name和name1。在调试器的结果视图中,我可以看到一个数组,数组中的每个项都包含一个
MongoDB.Bson.BsonDocument


我想用点表示法访问数组中每个BsonDocument的属性。如何实现这一点。

要从
BsonDocument
中获取值,可以使用
GetValue
/
TryGetValue
方法或索引器:

foreach (var document in results)
{
    var name1 = document.GetValue("name1");
    var name = document["name"];
}

当我不得不处理原始的BsonDocuments时遇到了这个问题。此解决方案允许您使用点表示法

没有完全测试或其他任何东西,但可能有用

void Main()
{
    var example = new BsonDocument{
        { "customer", new BsonDocument { { "email" , "homerjay@simpsons.com" } }}
    };

    var email = example.GetPath("customer.email").AsString;

    Console.WriteLine(email);
}

public static class MongoDbHelper
{
    public static BsonValue GetPath(this BsonValue bson, string path)
    {
        if (bson.BsonType != BsonType.Document)
        {
            throw new Exception("Not a doc");
        }

        var doc = bson.AsBsonDocument;

        var tokens = path.Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

        if (tokens.Length == 0 )
        {
            return doc;
        }

        if (!doc.Contains(tokens[0]))
        {
            return BsonNull.Value;
        }

        if (tokens.Length > 1)
        {
            return GetPath(doc[tokens[0]], tokens[1]);
        } 

        return doc[tokens[0]];
    }
}

results
将包含10个文档,每个文档都具有
name1
name
\u id
属性。你是在问如何获取这些属性的值吗?是的,很抱歉没有正确地解释我自己。上面的代码有一个bug。我试图编辑它来修复它,但由于某种原因,它被拒绝作为对作者的评论。上述代码仅在给定路径深度小于2时有效。要修复此错误,请在path.Split的行中添加参数以将计数限制为2(
var tokens=path.Split(new[]{.'},2,StringSplitOptions.removeMptyEntries);
)。这样,
tokens[1]
包含路径的其余部分,并可用于任何深度的路径(
doc.GetPath(“o.ididex.ns”);