如何用MongoDB改变数组的顺序? [英] How to change order of array with MongoDB?

查看:868
本文介绍了如何用MongoDB改变数组的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to be able to increment and decrement the position of an element of an array in a MongoDB object.

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

I looked at the <update> API in the MongoDB API but could not find anything to let me do so.

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

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/update/position/

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆