如何使用MongoDB更改数组的顺序?

Ada*_*son 5 javascript mongoose mongodb node.js express

我需要能够增加和减少MongoDB对象中数组元素的位置。

<update>MongoDB API中查看了该API,但找不到任何让我这么做的东西。

我正在尝试使用findOneAndUpdate贯通Mongoose,我知道我试图向上或向下移动的元素的索引。

base64编码图像数组项的示例:

{ 
  images: [
    "img1",
    "img2",
    "img3"
  ]
}
Run Code Online (Sandbox Code Playgroud)

我想向上或向下移动“ img2”(但由于无处可去,因此“图像”应该不能向上推)。

如果我想向上推“ img2”,那么结果将是:

{ 
  images: [
    "img2",
    "img1",
    "img3"
  ]
}
Run Code Online (Sandbox Code Playgroud)

通过更改索引,交换或上推/下推来实现此目标都没有关系。

Jon*_*ler 6

就像@ blakes-seven所说的那样,您有两种方法可以做到:

抓取,更新和推送

db.images.find({ _id: '' }, { images : 1 })
.then(function(img) {
  var tmpImg = img.images[0];
  img.images[0] = img.images[1];
  img.images[1] = tmpImg;

  db.images.update({ _id: img._id }, { $set: { images: img.images } });
})
Run Code Online (Sandbox Code Playgroud)

使用$ position 直接更新(如果您在客户端上有映像并且知道索引)

db.images.update({ _id: '' }, { $push: { images: { $each: ['img2'] }, $position: 0 } } } )
.then(function() {
  db.images.update({ _id: '' }, {$unset: {'images.2': 1}})
});
Run Code Online (Sandbox Code Playgroud)

https://docs.mongodb.org/manual/reference/operator/update/position/

但是,我认为您应该重新设计存储图像的方式,例如使用虚拟顺序:

{
  images: [
    { base64: 'img1', order: 0, _id: 'img1' },
    { base64: 'img2', order: 1, _id: 'img2' },
    { base64: 'img3', order: 2, _id: 'img3' }
  ]
}
Run Code Online (Sandbox Code Playgroud)

这样,您可以使用虚拟订单索引对图像进行排序,仅使用_id对其进行更新,或者通过更改所有img2的顺序,删除或替换图像等来更新整个集合。

  • 是的,但是您不必将整个图像数组发送到数据库或要为其更新索引的图像,因此可以节省大量带宽并具有更好的性能 (2认同)