开发服务器:
我有两个表users
和questions
,user_id
存储在每个问题中。
无意中删除了一些用户,现在我想删除该用户不存在的问题,
delete from questions where q.id not in( select q.id from questions q inner join users u on u.id = q.user_id);
我认为上面的查询在 mysql 中可以做到这一点,但我想在 mongodb 中做到这一点。
我是 mongodb 的新手,我知道查找聚合函数可以进行连接,但我不知道如何执行上述查询。
最佳答案
我相信您必须使用 $lookup
和 aggregation
管道来获取用户不存在的所有问题,然后删除这些问题。
试试这个:
var pipeline = [{
"$lookup": {
"from": "users",
"localField": "user_id",
"foreignField": "_id",
"as": "user_id"
}
}, {
"$match": {
"user_id": {
"$size": 0
}
}
}
]
var cursor = db.questions.aggregate(pipeline);
// create a map to get _id of all the question where user doesnt exist
var ids = cursor.map(function (doc) { return doc._id; });
// remove all those questions
db.questions.remove({"_id": { "$in": ids }});
关于蒙戈数据库 : select all the questions which has no user record and delete it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62657217/