我需要能够递增和递减一个数组元素在 MongoDB
中的位置对象。
我查看了 <update>
API 中的 MongoDB API但找不到任何东西让我这样做。
我正在尝试使用 findOneAndUpdate
通过Mongoose
并且我知道我要向上或向下移动的元素的索引。
base64
的数组项示例编码图像:
{
images: [
"img1",
"img2",
"img3"
]
}
我想向上或向下移动,例如“img2”(但是“image”不能向上推,因为无处可去)。
如果我想将“img2”向上推,那么结果将是:
{
images: [
"img2",
"img1",
"img3"
]
}
无论我是通过更改索引、交换还是上推/下推来实现这一点都没有关系。
最佳答案
正如@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 } });
})
直接更新(如果您在客户端有图像并且知道索引),使用 $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/
但是,我认为您应该重新设计存储图像的方式,例如使用虚拟排序:
{
images: [
{ base64: 'img1', order: 0, _id: 'img1' },
{ base64: 'img2', order: 1, _id: 'img2' },
{ base64: 'img3', order: 2, _id: 'img3' }
]
}
这样,您可以使用虚拟顺序索引对图像进行排序,仅使用 _id 更新它们,或者通过更改所有 img2 的顺序、删除或替换图像等来更新整个集合。
关于javascript - 如何使用 MongoDB 更改数组的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35810951/