将元素从一个数组移动到另一个数组,使用相同的Mongo UpdateOne查询



我有以下数据模型:

"finances" : {
"futurePostings" : [ 
{
"description" : "test",
"orderId" : ObjectId("614702b9e98e83bc5d7d3d62")
}
],
"balance" : []
}

然后,我试图将futurePosting中的元素移动到balance。我可以从futureposts中删除它,但我无法弄清楚是否可以使用位置$操作符(或任何其他命令)通过相同的查询来推动这个相同的文档内部平衡。

db.collection.updateOne(
{
"finances.futurePostings.orderId": ObjectId(orderId),
},
{
$push: { "finances.balance": ?? },
$pull: {
"finances.futurePostings": { orderId: ObjectId(orderId) },
},
}
);

有可能吗?

这在常规更新查询中是不可能的,但您可以尝试从MongoDB 4.2开始使用聚合管道进行更新,

  • pull fromfuturePostings
    • $filter迭代futurePostings数组循环,检查不等于条件以移除orderId
  • push intobalance
    • $filter重复futurePostings数组的循环,检查是否等于条件和过滤器匹配orderId元素
    • $concatArrays连接当前balance数组和新元素从上面的过滤结果
db.collection.updateOne(
{ "finances.futurePostings.orderId": ObjectId(orderId) },
[{
$set: {
"finances.futurePostings": {
$filter: {
input: "$finances.futurePostings",
cond: {
$ne: ["$$this.orderId", ObjectId(orderId)]
}
}
},
"finances.balance": {
$concatArrays: [
"$finances.balance",
{
$filter: {
input: "$finances.futurePostings",
cond: {
$eq: ["$$this.orderId", ObjectId(orderId)]
}
}
}
]
}
}
}]
)

游乐场

最新更新