简体   繁体   中英

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. However I want to cut the element and paste it to other index. What I'm trying to say is this;

Example1

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

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

What are the changes;

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

Example2

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

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?

I want to do it with less amount of code with best efficient way. I don't know the tricks of 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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