首页 > 解决方案 > 如何使用 mongoose 在 MongoDB 中将元素从一个数组位置移动到另一个位置?

问题描述

我在 MongoDB 中有一个对象数组,我正在将特定元素 id(即 1)从其位置移动到具有 id(即 2)的元素下方。这样我们就可以得到 id 为 2 -> 1 -> 3 的元素。

const arr = [
  {
    id: 1,
    name: 'foo'
  },
  {
    id: 2,
    name: 'bar'
  },
  {
    id: 3,
    name: 'zoo'
  }
]

我所做的是使用 $pull 和 $push 但它给出了ConflictingUpdateOperators我不知道如何处理它。

updatedPlan = await Plan.findOneAndUpdate(
        { _id: req.params.id },
        {
          $pull: {
                    "arr": {
                        id: 1
                    }
          },
          $push: {
                  "arr" : {
                    $each: [{ id: 1, name: 'foo'}],
                    $position: 1
                  }
          },
      );

标签: node.jsmongodbmongoose

解决方案


在 MongoDB 4.2 或更高版本中,您可以使用聚合管道更新文档。在数组索引的$range上使用简单的$map ,您可以打乱这些索引并使用$arrayElemAt来构建一个新数组:

db.col.update({ _id: req.params.id }, [
    {
        $set: {
            arr: {
                $map: {
                    input: { $range: [ 0, { $size: "$arr" } ] },
                    in: {
                        $let: {
                            vars: {
                                newIndex: {
                                    $switch: {
                                        branches: [
                                            { case: { "$eq": [ "$$this", 0 ] }, then: 1 },
                                            { case: { "$lte": [ "$$this", 1 ] }, then: { $subtract: [ "$$this", 1 ] } },
                                        ],
                                        default: "$$this"
                                    }
                                }
                            },
                            in: {
                                $arrayElemAt: [ "$arr", "$$newIndex" ]
                            }
                        }
                    }
                }
            }
        }
    }
])

推荐阅读