简体   繁体   English

MongoDB C#Driver中的BsonValue和自定义类

[英]BsonValue and custom classes in MongoDB C# Driver

I'm trying to use $push in an update query in mongodb, with the c# driver. 我正在尝试使用c#驱动程序在mongodb中使用$push进行更新查询。

The Update.Push(...) method requires a string name (that's fine), and a BsonValue to be 'pushed'. Update.Push(...)方法需要一个字符串名称(这很好),并且BsonValue需要“推送”。 This is where I run into problems. 这是我遇到问题的地方。 I'm trying to push a non simple type to the field's array. 我正在尝试将非简单类型推送到字段的数组。

For example: { $push : { "arrayfield" : { "a" : 7, "b" : 12 } } } 例如: { $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. 这在Mongo控制台中运行良好,但我无法弄清楚如何将我的对象变成BsonValue。 I've tried BsonValue.Create(myObjectInstance) but that gives me an error saying the .NET type cannot be mapped to a BsonValue. 我已经尝试过BsonValue.Create(myObjectInstance)但是这给了我一个错误,说明.NET类型无法映射到BsonValue。

Am I missing something simple? 我错过了一些简单的事吗?

I know two approaches: 我知道两种方法:

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

  2. Or convert your class to BsonValue yourself via ToBsonDocument() extension method. 或者通过ToBsonDocument()扩展方法将您的类转换为BsonValue

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM