node.js - 如何使用 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
}
},
);
解决方案
在 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" ]
}
}
}
}
}
}
}
])
推荐阅读
- flutter - 错误:无法处理本地通知上的方法调用
- docker - 向 Traefik 添加自定义标头会产生奇怪的行为
- javascript - 对象构造函数,将信息从表单传递到 HTML
- python - 如何洗牌html字段?- django
- css - 图像周围的阴影效果而不是图像边框
- xml - Delphi 使用 XML 格式的 Rest Client 示例
- php - 如何在 bemusic 中增加服务器文件上传限制?
- salesforce - 产品详细信息页面销售人员中的开始缩放会议按钮
- linux - 在 Linux 上为 ping 命令指定 TTL 值
- python-3.x - 在熊猫数据框中将列拆分为具有不同长度的多列