我在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
}
},
);
答案 0 :(得分:1)
在MongoDB 4.2或更高版本中,您可以使用Aggregation Pipeline更新文档。在数组索引$map上使用简单的$range,您可以将这些索引改组并使用$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" ]
}
}
}
}
}
}
}
])