如何使用 MongoDB 更改数组的顺序? [英] How to change order of array with MongoDB?
问题描述
我需要能够增加和减少 MongoDB
对象中数组元素的位置.
I need to be able to increment and decrement the position of an element of an array in a MongoDB
object.
我查看了
I looked at the <update>
API in the MongoDB API but could not find anything to let me do so.
我正在尝试通过 Mongoose
使用 findOneAndUpdate
并且我知道我试图向上或向下移动的元素的索引.
I am trying to use findOneAndUpdate
through Mongoose
and I know the index of the element I am trying to shift up or down.
base64
编码图像的数组项示例:
An example of the array item of base64
encoded images:
{
images: [
"img1",
"img2",
"img3"
]
}
我想向上或向下移动,例如img2"(但图像"应该无法向上推,因为无处可去).
And I would like to move, for example "img2", up or down (but "image" should not be able to pushed up since there is nowhere to go).
如果我想推img2",那么结果将是:
If I wanted to push "img2" up then the result would be:
{
images: [
"img2",
"img1",
"img3"
]
}
我是否通过更改索引、交换或向上/向下推来实现这一点并不重要.
It doesn't matter if I achieve this through changing the index, swapping, or pushing up/down.
推荐答案
就像@blakes-seven 所说的,你有两种方法可以做到:
Like @blakes-seven said, you have two ways to do it:
抓取、更新和推送
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
Updating directly (if you have the image on the client and know the indexes), using $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/更新/位置/
但是,我认为您应该重新设计存储图像的方式,例如使用虚拟排序:
However, I think you should redesign the way you stores your images, using by example a virtual ordering:
{
images: [
{ base64: 'img1', order: 0, _id: 'img1' },
{ base64: 'img2', order: 1, _id: 'img2' },
{ base64: 'img3', order: 2, _id: 'img3' }
]
}
这样,您可以使用虚拟顺序索引对图像进行排序,仅使用 _id 更新它们,或者通过更改所有 img2 的顺序、删除或替换图像等来更新整个集合.
This way, you could order your images using a virtual order index, updating them using only the _id, or updating the whole collection by changing order of all img2, dropping or replacing an image, etc.
这篇关于如何使用 MongoDB 更改数组的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!