Header Ads Widget

Tìm và xóa dữ liệu trùng lặp trong MongoDB

Lệnh tìm những dữ liệu bị trùng, xuất hiện 2 lần. Sau đó xóa dữ liệu trùng, chỉ giữ lại 1 bản ghi đầu tiên

Câu lệnh thao tác bằng nodejs

Như trường hợp bên dưới là lọc tìm ra những shop_id, rule trùng lặp xuất hiện 2 lần

let pipeline = [

        {

            $match: {

                type: 7,

                // shop_id: mongoose.Types.ObjectId('641a7d1b74c25f45be7b3833')

            }

        },

        {

            $group: {

                _id: { shop_id: "$shop_id", rule: "$rule" },

                count: { $sum: 1 },

                docs: { $push: "$_id" }

            }

        },

        {

            $match: {

                count: { $gt: 1 }

            }

        }

    ];

    // pipeline.push({ $limit: 1 });

    let duplicates = await Keyword.getPipe(pipeline);

    for (const group of duplicates) {

        const [keepId, ...deleteIds] = group.docs;

        for(let _id of deleteIds){

            await Keyword.removeData({ _id});

            console.log("== XÓA ID = "+ _id);

        }

    } 

Nhận xét