gpt4 book ai didi

php - 如何以原子方式重新排序 MongoDB 中的数组项?

转载 作者:可可西里 更新时间:2023-11-01 10:44:47 24 4
gpt4 key购买 nike

我有一个播放列表 集合。集合中的每个文档都包含一个 entries 字段,即一个数组。

如何自动更改播放列表中 entries 的顺序?(例如,如果另一个用户同时尝试$push一个新条目,我想确保新条目是$push仅在重新排序发生后编辑)

如果我执行 find(),然后在 PHP 中重新排序,然后是 update(),我可能会丢失新的 $pushed如果操作不是原子的,则进入。

这是一个示例播放列表对象:

{
"_id" : "playlist1",
"title" : "Playlist One",
"entries" : [
{
"class" : "song",
"identifier" : "song1"
},
{
"class" : "song",
"identifier" : "song2"
},
{
"class" : "song",
"identifier" : "song3"
}
]
}

编辑:

我想我找到了一个可能的解决方案,使用 execute():

Running JavaScript in the database takes a write lock, meaning it blocks other operations.

(来自 http://php.net/manual/en/mongodb.execute.php)

我只需要在 MongoDB 服务器上执行代码 (find() + reorder() + update())。

不过,如果您有另一个不涉及“字符串中的代码”的想法(例如 $func = "function() { do_something(); return\"something else\"}"), 请分享。

谢谢!

最佳答案

使用 eval() 来阻止操作是当前实现的副作用,而不是可以依赖的功能。

MongoDB wiki 有一个页面包含关于 Atomic Operations 的信息.

您的用例的相关策略是 "update if current" :

  1. 获取对象。
  2. 在本地修改对象。
  3. 发送更新请求,内容为“如果对象仍与其旧值匹配,则将对象更新为此新值”。

关于php - 如何以原子方式重新排序 MongoDB 中的数组项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7791114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com