簡體   English   中英

Mongodb: select 所有沒有用戶記錄的問題並刪除

[英]Mongodb : select all the questions which has no user record and delete it

開發服務器:

我有兩個表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 的新手,我知道查找聚合 function 進行連接,但我不知道如何進行上述查詢。

為此確實需要$lookup ,但您需要另一個管道階段,即$match以僅獲取userId計數為0的那些文檔(我們希望在我們的結果集中有userId長度為> 0的文檔> 0因為這意味着user_id存在於users )。

使用來自aggregation的結果集,您可以進行簡單的迭代並remove保留在集合中的所有文檔。 像這樣的東西應該這樣做(因為我現在無法測試它,也許可以快速測試一下):

db.getCollection('questions').aggregate([{
            "$lookup": {    
                "from": "users",
                "localField": "user_id",
                "foreignField": "user_id",
                "as": "userId"    
            }
        }, {
            "$match": {
                "userId": {
                    "$size": 0
                }
            }
        },

    ]).forEach((doc) => {
        db.getCollection("questions").remove({ "_id": doc._id });
    });

除了最后一部分中的forEach ,您還可以獲得所有id並像 Ravi 那樣在一個單獨的remove -query 中刪除它們。

我相信您將不得不使用$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 }});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM