【问题标题】:Cut and paste the array elements in most efficient way以最有效的方式剪切和粘贴数组元素
【发布时间】:2016-03-09 22:17:17
【问题描述】:

我知道$pull和$push可以用来更新mongodb中的数组元素。 但是我想剪切元素并将其粘贴到其他索引。 我想说的是这个;

示例 1

假设我有

var arr = [a , b, c, d, e];

我想把元素 e 放在索引 0 处。现在应该是

var arr  = [e, a , b, c, d];

有什么变化;

Indices of (a b c d) increase by 1. 

示例2

假设我有

var arr = [a , b, c, d, e];

我想剪切元素 b 并将其粘贴到索引 3。现在应该是

var arr  = [a , c, d, b, e];

有什么变化;

Indices of (c d) decrease by 1. 

我怎样才能以最有效的方式处理它?取存储它的子数组,然后重新创建 arr 数组?

我想以最有效的方式用更少的代码来完成它。我不知道mongodb的技巧。我检查了the documentation,但找不到最好的解决方案。你怎么看?

【问题讨论】:

    标签: javascript arrays node.js algorithm mongodb


    【解决方案1】:

    第一部分:

    var arr  = [a , b, c, d, e];
    
    var item = arr.slice(2,1);
    
    arr.push(item);
    

    第二部分:

    var arr = [a , b, c, d, e];
    
      var items = arr.slice(2,2);
    
      arr.splice(4,0,items[0], items[1]);
    

    【讨论】:

    • 谢谢,但这些只是示例,索引将是动态的。
    • 您不必对参数值进行硬编码
    【解决方案2】:

    为了限制对特定索引的更改,我相信您可能正在寻找 $slice

    【讨论】:

      【解决方案3】:

      给定文档,

      > db.history.find({})
      { "_id" : ObjectId("56e02e2c319d15b8fd9c6e69"), "arr" : ["a", "b", "c", "d", "e" ] }
      

      使用以下两个命令,通过$pull 从数组中剪切或取出元素,然后通过$push 和$position 将其过去或放置

      > db.history.update({}, {$pull: {arr: 'e'}})
      WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
      > db.history.update({}, {$push: {arr: {$each: ['e'], $position: 0}}})
      WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
      

      结果

      > db.history.find({})
      { "_id" : ObjectId("56e02e2c319d15b8fd9c6e69"), "arr" : [ "e", "a", "b", "c", "d" ] }
      

      第二个例子的逻辑相同

      > db.history.update({}, {$pull: {arr: 'b'}})
      > db.history.update({}, {$push: {arr: {$each: ['b'], $position: 3}}});
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-17
        • 1970-01-01
        • 2014-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多