繁体   English   中英

以最有效的方式剪切和粘贴数组元素

[英]Cut and paste the array elements in most efficient way

我知道$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的窍门。 我检查了文档,但找不到最佳解决方案。 你怎么看?

对于第一部分:

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]);

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

给定文件,

> 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}}});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM