问题描述
我试图用 $推
在MongoDB中更新查询,用C#的驱动程序。
I'm trying to use $push
in an update query in mongodb, with the c# driver.
在 Update.Push(...)
方法需要一个字符串名称(这很好),以及被推一BsonValue。这是我遇到的问题。 。我试图推动非简单类型的字段的阵列
The Update.Push(...)
method requires a string name (that's fine), and a BsonValue to be 'pushed'. This is where I run into problems. I'm trying to push a non simple type to the field's array.
例如: {$推:{arrayfield:{一:7,b:12}}}
这在蒙戈控制台工作正常,但我想不出如何让我的对象变成BsonValue。我试过 BsonValue.Create(myObjectInstance)
但是这给了我一个错误说的.NET类型不能映射到BsonValue。
This works fine in the Mongo console, but I can't figure out how to make my object into a BsonValue. I've tried BsonValue.Create(myObjectInstance)
but that gives me an error saying the .NET type cannot be mapped to a BsonValue.
我失去了一些东西简单
推荐答案
我知道两种方法:
-
Update.PushWrapped<为MyObject>(arrayfield,myObjectInstance);
// C#驱动程序> = 1.0
Update.PushWrapped<MyObject>("arrayfield", myObjectInstance);
//c# driver >= 1.0
通过 ToBsonDocument或者你的类转换为
扩展方法 BsonValue
自己()
Or convert your class to BsonValue
yourself via ToBsonDocument()
extension method.
Update.Push(arrayfield,myObjectInstance.ToBsonDocument());
这篇关于BsonValue和自定义类在MongoDB中C#驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!