修改MongoDB中数组的最后一个元素 [英] Modifying the last element of an array in MongoDB

查看:598
本文介绍了修改MongoDB中数组的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的对象结构:

I have an object structure like this:

 {
    name: "...",
    pockets: [
        {
            cdate: "....",
            items: [...]
        }
        ...
    ]
 }

在更新操作中,我想向最后一个 pocket 项目的 items 字段中添加一些记录.使用点表示法是我知道访问子文档的唯一方法,但是我无法获得所需的信息.所以,我正在寻找类似这样的东西:

In an update operation, I want to add some records into the items field of the last pocket item. Using dot notation is the only way that I know to access a sub document, but I can't get what I want. So, I'm looking for something like these:

  • pockets.-1.items
  • pockets.$ last.items

是否可以修改最后一个元素?如果是,怎么办?

Is it possible to modify the last element? If yes, how?

推荐答案

我不认为可以原子地做到这一点. 请求,此功能将添加到MongoDB.

I don't believe it is possible to do it atomically. There is a request for this functionality to be added to MongoDB.

如果您可以确保应用代码中的线程安全性,则可以从Pockets数组中使用$ pop序列(从Pocket中删除最后一个元素)到变量p,然后再使用$ addToSet到p.items,现在您可以将p推回口袋了.但是,如果您的应用程序无法确保一次只能有一个进程在执行此操作,那么另一个进程可能会在这些步骤的中间修改数组,最终可能会丢失该更新.

If you can assure thread-safety in your application code, you could probably use a sequence of $pop from pockets array (that removes the last element from pockets) to variable p and then $addToSet to p.items, now you can $push p back into pockets. But if your application doesn't have a way to assure only one process may be doing this at one time, then another process could modify the array in the middle of those steps and you may end up losing that update.

您还可以在此处中查看如果当前更新"另一种解决多线程问题的方法.

You might also look into "Update if current" semantics here to see another way you can work around possible race by multiple threads issue.

这篇关于修改MongoDB中数组的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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