如何删除mongodb中聚合查询返回的文档 [英] How to delete documents returned by an aggregation query in mongodb
问题描述
我正在尝试删除 Mongodb 中的聚合返回的所有文档.
I am attempting to delete all the documents returned by an aggregation in Mongodb.
我的查询如下:
db.getCollection("Collection")
.aggregate([
{
$match: { status: { $in: ["inserted", "done", "duplicated", "error"] } }
},
{
$project: {
yearMonthDay: { $dateToString: { format: "%Y-%m-%d", date: "$date" } }
}
},
{ $match: { yearMonthDay: { $eq: "2019-08-06" } } }
])
.forEach(function(doc) {
db.getCollection("Collection").remove({});
});
我试过这个查询,但它删除了数据库中的所有数据,请问有什么建议吗?
I tried this query but it removes all the data in the database, any suggestions please?
推荐答案
由于 remove 没有查询条件,它会与所有文档匹配并删除,而不管聚合结果如何.
Since the remove doesn't have a query condition its going to match with all the documents and delete irrespective of the aggregation result.
解决方案(匹配当前光标文档的id):
Solution (match the ids of the current cursor doc):
db.getCollection("Collection")
.aggregate([
{
$match: { status: { $in: ["inserted", "done", "duplicated", "error"] } }
},
{
$project: {
yearMonthDay: { $dateToString: { format: "%Y-%m-%d", date: "$date" } }
}
},
{ $match: { yearMonthDay: { $eq: "2019-08-06" } } }
])
.forEach(function(doc) {
db.getCollection("Collection").remove({ "_id": doc._id });
});
另一个更好的解决方案是对db进行单次往返,而删除是从聚合中获取id列表cursor()
通过 cursor.map()
Another better solution would be to have single round trip to db while deletion is get a list of ids from the aggregation cursor()
via cursor.map()
var idsList = db
.getCollection("Collection")
.aggregate([
{
$match: { status: { $in: ["inserted", "done", "duplicated", "error"] } }
},
{
$project: {
yearMonthDay: { $dateToString: { format: "%Y-%m-%d", date: "$date" } }
}
},
{ $match: { yearMonthDay: { $eq: "2019-08-06" } } }
])
.map(function(d) {
return d._id;
});
//now delete those documents via $in operator
db.getCollection("Collection").remove({ _id: { $in: idsList } });
这篇关于如何删除mongodb中聚合查询返回的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!