是否有一种强类型的方式来更新 MongoDB 中的子文档? [英] Is there a strongly-typed way to update a subdocument in MongoDB?

查看:38
本文介绍了是否有一种强类型的方式来更新 MongoDB 中的子文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Mongo 中更新一个子文档,我就是这样做的.此屏幕截图显示了我的文档的外观.下面的代码显示了我如何更新 Geddy 的名字和乐器.

I have the need to update a subdocument in Mongo, and this is how I did it. This screenshot shows what my documents look like. And the code below it shows how I updated Geddy’s name and instrument.

注意:此方法取自这篇 SO 帖子:

var update = Update.Set("Members.$.Instrument", "Keyboards").Set("Members.$.LastName", "Leex");

var collection = MongoDbHelper.Db.GetCollection<Band>("Bands");
collection.Update(Query.And(Query.EQ("Name", "Rush"), Query.EQ("Members.FirstName", "Geddy")), update);

是否有另一种/更好的方法来使用强类型属性而不是所有这些字符串文字?

推荐答案

目前不支持使用 typed 编写查询或更新(即查询数组的各个子字段并在更新中使用$")建设者.

There is currently no support for writing queries or updates like this one (i.e. querying against individual subfields of arrays and using "$" in the update) using the typed builders.

难点在于提出可以正确编译且正确表达所需意图的表达式.

The difficulty is coming up with expressions that compile without errors and yet express the desired intent correctly.

例如,以下可能是一个可行的设计,但使用 -1 作为索引值有点麻烦:

For example, the following might be a workable design, but using -1 as an index value is kind of hacky:

var query = Query.And(
    Query<Band>.EQ(b => b.Name == "Rush"),
    Query<Band>.EQ(b => b.Members[-1].FirstName == "Geddy"));
var update = Update<Band>
    .Set(b => b.Members[-1].Instrument, "Keyboards")
    .Set(b => b.Members[-1].LastName, "Leex");

注意:这只是在类型化构建器中支持$"的一种可能设计.它实际上并没有以这种方式实现.

Note: this is just a possible design for supporting "$" in typed builders. It is not actually implemented this way.

如果您对如何表达类型安全版本有任何想法,您应该创建一个 JIRA 票证来建议该功能.

If you have any ideas for how a type safe version of this could be expressed you should create a JIRA ticket suggesting the feature.

这篇关于是否有一种强类型的方式来更新 MongoDB 中的子文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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