且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何更新使用C#驱动程序在MongoDB中包含在数组中的子文档在数组中的子文档的字段?

更新时间:2022-11-13 22:30:00

这@Disposer回答帮我找到了一个解决方案。它传播的多个领域,我的代码库,但我想与他人分享的基本精神谁可能有类似的问题。

Answer from @Disposer helped me find a solution for this. It spreads multiple areas in my codebase but I would like to share the basic gist with others who may have a similar problem.

这些步骤如下:


  • 锁定给定的顺序,不要让物品添加进去(在应用程序级别)。

  • 另外,使用一个额外的 WriteCount 字段的组合,并使用 findAndModify 以原子更新文档仅当它尚未在此期间被更新(更新,如果当前)。

  • Lock the given Order and do not allow items to be added into it (on application level).
  • Alternatively, use a combination of an additional WriteCount field and by using findAndModify to atomically update the document only if it has not been updated in the meantime ("update if current").

然后,当更新标题对于给定的项目:

Then, when updating Title for a given item:


  • 使用存储 WriteCount

  • 确定项指数

  • 使用相结合的项目索引与位置运算符: $ 来标识会话,一个整数首页为目标的项目,同时聘请更新,如果目前的战略使用 WriteCount 字段

  • use stored WriteCount
  • determine item index
  • use the item index in combination with the positional operator: $ to identify the session, an integer index to target the item, while employing "update if current" strategy using the WriteCount field.

然后将更新的部分就变成了:

The update part then becomes:

"Sessions.$.Order.Items." + index + ".Title"