开发者

BsonValue and custom classes in MongoDB C# Driver

开发者 https://www.devze.com 2023-04-12 14:00 出处:网络
I\'m trying to use $push in an update query in mongodb, with the c# driver. The Update.Push(...) method requires a string name (that\'s fine), and a BsonValue to be \'pushed\'.This is where I run int

I'm trying to use $push in an update query in mongodb, with the c# driver.

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 simp开发者_如何学运维le type to the field's array.

For example: { $push : { "arrayfield" : { "a" : 7, "b" : 12 } } }

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.

Am I missing something simple?


I know two approaches:

  1. Update.PushWrapped<MyObject>("arrayfield", myObjectInstance); //c# driver >= 1.0

  2. Or convert your class to BsonValue yourself via ToBsonDocument() extension method.

    Update.Push("arrayfield", myObjectInstance.ToBsonDocument());

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号