我有以下数据模型:
"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 from
futurePostings
$filter
迭代futurePostings
数组循环,检查不等于条件以移除orderId
- push into
balance
$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)]
}
}
}
]
}
}
}]
)
游乐场