如何删除作为聚合结果返回的所有 chunks
文档?
db.getCollection('chunks').aggregate([
{
$lookup:
{
from: "files",
localField: "files_id",
foreignField: "_id",
as: "file"
}
},
{
$match:
{
"file.uploadDate":
{
$lt: ISODate("2017-06-10T00:00:00.000Z")
}
}
}
])
我的模式有一个名为 files
的集合,其中包含文件元数据(名称、上传日期)和 block ,其中包含实际数据(二进制、files_id)
我知道 db.collection.deleteMany({})
但是它只接受匹配过滤器。
我有 MongoDB 3.2
最佳答案
循环结果:
var ops = [];
db.getCollection('chunks').aggregate([
{
$lookup:
{
from: "files",
localField: "files_id",
foreignField: "_id",
as: "file"
}
},
{
$match:
{
"file.uploadDate":
{
$lt: ISODate("2017-06-10T00:00:00.000Z")
}
}
}
]).forEach(doc => {
ops = [
...ops,
{ "deleteOne": {
"filter": { "_id": doc._id }
}}
];
if ( ops.length >= 1000 ) {
db.getCollection('chunks').bulkWrite(ops);
ops = [];
}
});
if ( ops.length > 0 ) {
db.getCollection('chunks').bulkWrite(ops);
ops = [];
}
或者在没有 ES6 的环境中:
var ops = [];
db.getCollection('chunks').aggregate([
{
$lookup:
{
from: "files",
localField: "files_id",
foreignField: "_id",
as: "file"
}
},
{
$match:
{
"file.uploadDate":
{
$lt: ISODate("2017-06-10T00:00:00.000Z")
}
}
}
]).forEach(function(doc) {
ops.push({ "deleteOne": { "filter": { "_id": doc._id } } });
if ( ops.length >= 1000 ) {
db.getCollection('chunks').bulkWrite(ops);
ops = [];
}
});
if ( ops.length > 0 ) {
db.getCollection('chunks').bulkWrite(ops);
ops = [];
}
使用 .bulkWrite()
那么您基本上是以 1000 个为单位“批处理”请求。因此来自数据库的实际写入和响应仅在那时发生,而不是针对所有条目。
您不能提供聚合管道作为一般 .remove**()
方法的查询参数。所以你要做的是用这样的 Action 循环光标。
关于mongodb - 删除 mongodb $lookup 聚合的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44515751/