如何使用C#从MongoDB中的数组检索值 [英] How to retrieve values from an array in MongoDB using C#

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

问题描述

下面的代码以BsonArray的形式检索元素.我只想从数组中获取数字值,然后使用该值来计算总和.

Below in the code that retrieves the elements in the form of a BsonArray. I just want to fetch the numeric value from the array and use that value to calculate the sum.

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

我尝试将bson元素转换为int64,int32,double,然后使用数字值进行加法,但出现运行时错误,无法转换bsonarray等.有人对此有任何想法吗? ?

I tried converting the bson element to an int64, int32, double and then use the numeric value for addition but i get a runtime error of not able to cast a bsonarray etc. Does anyone have any idea on how to go about this?

推荐答案

我通过进行以下更改找到了解决方案,现在它可以正常工作:

I figured out the solution, by making the following changes and it works now:

foreach (BsonDocument nestedDocument in Document["name"].AsBsonArray)
                        {
                            Total += Convert.ToDouble(nestedDocument["amount"]);
                        }

这篇关于如何使用C#从MongoDB中的数组检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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