如何在MongoDB数组中移动项目? [英] How to move an item in a MongoDB array?

查看:87
本文介绍了如何在MongoDB数组中移动项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以更新文档数组以将项目从一个索引移动到另一个索引? 例如

Is there a way to update a document array to move an item from one index to another? e.g.

{
   name: "myDoc",
   items: ["it1", "it2", "it3"]
}

作为JQuery-UI Sortable事件的结果,it2和it3切换了位置.因此,我想更新它们在存储在MongoDB中的myDoc中的位置.

As a result for JQuery-UI Sortable event it2 and it3 switched places. As a result I want to update their position in the myDoc which is stored in MongoDB.

推荐答案

这是将元素移动到新位置的另一种方法,它将交换it2和it3的位置...

Here is another way to move an element to a new position which will swap the positions of it2 and it3...

  1. 使用$ pull从数组中删除元素 [Docs Here ] .

update({"name": "myDoc"}, {$pull: {"items" : "it3"}});

  • 使用$ push将元素插入新位置. [此处的文档] .

    update({"name": "myDoc"}, { 
        $push: { 
            "items" : { $each : [ "it3" ], $position : 1 }
        }
    });
    

  • 何时使用

    对于许多用例,Pouzor使用$ set的答案可能更简单,并且性能更好.

    Pouzor's answer to use $set might be simpler and perform better for many use cases.

    但是,如果多个用户同时添加,删除和重新排序数组项,则此方法意味着您不会覆盖彼此的更改.

    However, if multiple users are simultaneously adding, removing, and re-ordering array items this method means you won't overwrite each other's changes.

    在某些情况下(例如大型数组元素),由于写入的数据较少,因此效率可能更高.

    It might also be more efficient in some cases (e.g. large array elements) because less data is being written.

    GOTCHA:列表列表

    如果要重新排序的列表是一个数组数组,则需要将$ all运算符与$ pull一起使用

    If the list you are reordering is an array of arrays you need to use the $all operator with $pull [ Docs Here ]

    以这个例子为例:

    {
        name: "myDoc",
        items: [  
            [ "User", "dofij20r91dj93" ],   
            [ "User", "239vjvidjfsldf" ], 
            [ "User", "2309jvdsjdkk23" ]
        ]
    }
    

    以下是从列表列表中删除第一个列表的代码:

    Here's the code to remove the first list from the list of lists:

    update({"name": "myDoc"}, {
        $pull: {
            "items" : {
                $all : [ "User", "dofij20r91dj93" ]  // the sub-list to $pull
            }
        }
    });
    

    对象列表

    这很容易.假设您具有以下对象列表:

    This is easy. Say you have the following list of objects:

    {
        name: "myDoc",
        items: [  
            { type: "User",  id: "dofij20r91dj93", name: "Dave" },   
            { type: "Group", id: "239vjvidjfsldf", name: "Accountants" }, 
            { type: "User",  id: "2309jvdsjdkk23", name: "Toni" }
        ]
    }
    

    您可以像这样$ pull:

    You can $pull like this:

    update({"name": "myDoc"}, {
        $pull: { 
            "items" : { type: "User", id: "dofij20r91dj93" } 
        }
    });
    

    这篇关于如何在MongoDB数组中移动项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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