如何用MongoDB改变数组的顺序?

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

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

我试图通过Mongoose使用findOneAndUpdate ,我知道我想要上下移动的元素的索引。

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

 { images: [ "img1", "img2", "img3" ] } 

我想动一下,例如“img2”,上下(但是“形象”不应该因为无处可去而被推高)。

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

 { images: [ "img2", "img1", "img3" ] } 

如果我通过改变索引,交换或上/下来实现这一点并不重要。

像@布莱克斯 – 七说,你有两种方式来做到这一点:

攫取,更新和推动

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

直接更新 (如果你有客户端的图像,并知道索引),使用$ position

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

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

不过,我认为您应该重新devise您存储图像的方式,例如使用虚拟sorting:

 { images: [ { base64: 'img1', order: 0, _id: 'img1' }, { base64: 'img2', order: 1, _id: 'img2' }, { base64: 'img3', order: 2, _id: 'img3' } ] } 

这样,您可以使用虚拟订单索引来订购图像,仅使用_id更新它们,或通过更改所有img2的顺序来更新整个集合,删除或replace图像等。