蒙戈数据库 : select all the questions which has no user record and delete it

标签 mongodb

开发服务器:

我有两个表usersquestionsuser_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 的新手,我知道查找聚合函数可以进行连接,但我不知道如何执行上述查询。

最佳答案

我相信您必须使用 $lookupaggregation 管道来获取用户不存在的所有问题,然后删除这些问题。

试试这个:

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/

相关文章:

python - Mongo 查询中的 AND 和 OR

node.js - 没有 Express Js 和 Nodejs 的带有 Angular JS 的 MongoDB

MongoDB:如何查找仅包含最新更改信息的文档?

mongodb - Mongo查询数组是子数组

node.js - 基于带有值的动态日期键的 Mongoose 过滤器

python - MongoDB - 将带有数组的一条记录转换为新集合中的多条记录

python - 在 PyMongo 中使用 IS NULL

node.js - 在Express路由而不是Mongoose.connect回调中检测Mongoose/MongoDB错误

javascript - Mongoose : Dynamically load different schema under one collection

mongodb - 集成 Google App Engine 和 Compute MongoDB,可能吗?