如何根据二进制字段大小有选择地删除MongoDB集合中文档中的字段?
How to selectively remove field in documents in MongoDB collection according to binary field size?
我找到了 $binarySize,但它只能应用于聚合查询,这形成了全新的集合,这不是我要更改的数据集本身。
我看不到将 $binarySize 与 find() 一起使用的方法。
我的聚合查询是这样的:
db.releases_details.aggregate([
{ $project: { release_id: "$release_id", cover: "$cover", img: "$img", tracklist: "$tracklist", imageSize: { $binarySize: "$cover" } } },
{ $match: { "imageSize": { $lt: 1775 } } }
])
示例数据如下:
{ "_id" : ObjectId("623ebe3315e29330ede4e631"), "release_id" : 43239, "cover" : BinData(0,"PCFET0NUWVBFIGh0bWw+CjxodG1sIGxh... (1,555 bytes)") },
{ "_id" : ObjectId("623ebe3315e29330ede4e630"), "release_id" : 43238, "cover" : BinData(0,"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD... (42,200 bytes - image/jpeg)") }
如果我可以将小于 1775 字节的 cover 属性 设置为 null 就好了?
有人做过类似的事情吗?
您可以使用 $cond
来操作 cover
字段。然后使用 $merge
通过聚合管道更新回集合。
db.collection.aggregate([
{
"$addFields": {
"cover": {
"$cond": {
"if": {
$lt: [
{
"$binarySize": "$cover"
},
1775
]
},
"then": null,
"else": "$cover"
}
}
}
},
{
"$merge": {
"into": "collection",
"on": "_id",
"whenMatched": "replace"
}
}
])
这里是Mongo playground供您参考。
我找到了 $binarySize,但它只能应用于聚合查询,这形成了全新的集合,这不是我要更改的数据集本身。
我看不到将 $binarySize 与 find() 一起使用的方法。
我的聚合查询是这样的:
db.releases_details.aggregate([
{ $project: { release_id: "$release_id", cover: "$cover", img: "$img", tracklist: "$tracklist", imageSize: { $binarySize: "$cover" } } },
{ $match: { "imageSize": { $lt: 1775 } } }
])
示例数据如下:
{ "_id" : ObjectId("623ebe3315e29330ede4e631"), "release_id" : 43239, "cover" : BinData(0,"PCFET0NUWVBFIGh0bWw+CjxodG1sIGxh... (1,555 bytes)") },
{ "_id" : ObjectId("623ebe3315e29330ede4e630"), "release_id" : 43238, "cover" : BinData(0,"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD... (42,200 bytes - image/jpeg)") }
如果我可以将小于 1775 字节的 cover 属性 设置为 null 就好了?
有人做过类似的事情吗?
您可以使用 $cond
来操作 cover
字段。然后使用 $merge
通过聚合管道更新回集合。
db.collection.aggregate([
{
"$addFields": {
"cover": {
"$cond": {
"if": {
$lt: [
{
"$binarySize": "$cover"
},
1775
]
},
"then": null,
"else": "$cover"
}
}
}
},
{
"$merge": {
"into": "collection",
"on": "_id",
"whenMatched": "replace"
}
}
])
这里是Mongo playground供您参考。