简体   繁体   English

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

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

I know that $pull and $push can be used to update array elements in mongodb. 我知道$pull$push可用于更新mongodb中的数组元素。 However I want to cut the element and paste it to other index. 但是我想剪切元素并将其粘贴到其他索引。 What I'm trying to say is this; 我想说的是这个。

Example1 例1

Let's assume I have 假设我有

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

I want to take element e and place it at index 0. Now it should be 我想将元素e放在索引0处。现在应该是

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

What are the changes; 有什么变化;

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

Example2 例2

Let's assume I have 假设我有

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

I want to cut element b and paste it at index 3. Now it should be 我想剪切元素b并将其粘贴到索引3。现在应该是

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

What are the changes; 有什么变化;

Indices of (c d) decrease by 1. 

How can I handle it in a most efficient way? 如何以最有效的方式处理它? Take the subarray that store it, then recreate the arr array? 采取存储它的子数组,然后重新创建arr数组?

I want to do it with less amount of code with best efficient way. 我想用最少的代码来实现最佳效率。 I don't know the tricks of mongodb. 我不知道mongodb的窍门。 I checked the documentation but couldn't find the best solution for this. 我检查了文档,但找不到最佳解决方案。 What do you think? 你怎么看?

for part one: 对于第一部分:

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

var item = arr.slice(2,1);

arr.push(item);

for part two: 对于第二部分:

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

  var items = arr.slice(2,2);

  arr.splice(4,0,items[0], items[1]);

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

Given the document, 给定文件,

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

With the following two commands, cut or take element from array through $pull , then past or place it through $push and $position 使用以下两个命令,通过$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 })

Result 结果

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

Same logic for your second example 第二个示例的逻辑相同

> 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