簡體   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