MongoDb - 删除符合两个条件的重复项

时间:2021-07-01 06:37:12

标签: node.js mongodb mongoose aggregation-framework

我有一个名为 business 的集合。商业模式如下:

name: {
  type: String,
},
email: {
  type: String,
},
views: {
  type: Number
}
location: {
  lat: Number,
  lon: Number,
}

有些企业名称相同,但位于不同的地点,我对此表示同意。然而,其中一些具有相同的名称并且仍然具有相同的位置(location.lat 和 location.long),此类企业是我想从中删除重复项的企业。我见过的大多数解决方案只处理一个字段匹配,我该如何处理两个字段匹配的重复项,我想总结匹配的视图

const businesses = await Business.aggregate([
            {
                $match: {
                    name: {
                        $ne: true,
                    },
                    location: {
                        $ne: true,
                    },
                },
            },
            {
                $group: {
                    _id: { name: "$name" }, // can be grouped on multiple properties
                    dups: { $addToSet: "$_id" },
                    count: { $sum: 1 },
                },
            },
            {
                $match: {
                    count: { $gt: 1 }, // Duplicates considered as count greater than one
                },
            },
        ]);

1 个答案:

答案 0 :(得分:0)

在您的代码中,您没有在 location 语句中考虑 $group

const businesses = await Business.aggregate([
            {
                $match: {
                    name: {
                        $ne: true,
                    },
                    location: {
                        $ne: true,
                    },
                },
            },
            {
                $group: {
                    _id: { 
                      name: "$name",
                      location: "$location",  // <-- Add location too to be considered in the group
                    },
                    dups: { $push: "$_id" },  // <-- Changed from `$addToSet` to push since `_id` is alreadr unique and `$push` is faster than `$addToSet`
                    count: { $sum: 1 },
                },
            },
            {
                $match: {
                    count: { $gt: 1 },
                },
            },
        ]);