模式:
{
img: // array of minimum length 1 of ObjectIds or field is "missing" to indicate that array is empty
tar: [
{ img: // array of minimum length 1 of ObjectIds or field is "missing" to indicate that array is empty },
{ img: // array of minimum length 1 of ObjectIds or field is "missing" to indicate that array is empty },
...
]
}
这是我删除照片的查询,它是顶级img
数组中的ObjectId,并且可能在某些tar
子文档的img
字段中:
await mongo_tran_ses.withTransaction(async () => {
// pulling the ObjectId matching `req.params._id` from `img`, and all `tar.img`
await user.updateOne(
{ _id: ObjectId(req.user._id) },
{
$pull: {
img: { _id: { $eq: ObjectId(req.params._id) } },
"tar.$[].img": { $eq: ObjectId(req.params._id) },
},
},
{ session: mongo_tran_ses }
);
// removing all `tar.img` if it is now an empty array
await user.updateOne(
{
_id: ObjectId(req.user._id),
},
{
$unset: {
"tar.$[element].img": "",
},
},
{
arrayFilters: [{ "element.img": { $size: 0 } }],
session: mongo_tran_ses,
}
);
// removing `img` if it is now an empty array
await user.updateOne(
{
_id: ObjectId(req.user._id),
img: { $size: 0 },
},
{
$unset: {
img: undefined,
},
},
{
session: mongo_tran_ses,
}
);
}, tran_option);
目标:
只使用一个update
查询而不是上面的3个查询来执行上面的操作。
2条答案
按热度按时间iklwldmw1#
这是如何在mongo shell 4.2+中完成的:
解释:
1.通过$map/$filter对img.tar.img[]进行项目/AddField操作以删除元素(示例中为2)
1.要删除的项目/addFields(如果有空img.tar.img[])(如果有)
1.要删除的项目/addFields(如果有空img.tar[])(如果有)
1.要再次删除的项目/addFields空img:[](如果有)
Playground
ndh0cuux2#
Abit后来看到你的schema是不同的,这里是img[]和tar.img[]作为不同字段的选项:
解释:
1.从img[]中删除id:2
1.从tar.img[]中删除id:2
Playground