【问题标题】:MongoDb - Remove duplicates matching two criteriaMongoDb - 删除匹配两个条件的重复项
【发布时间】:2021-07-01 14:56:15
【问题描述】:

我有一个名为业务的集合。商业模式是这样的:

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
                },
            },
        ]);

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework


    【解决方案1】:

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

    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 },
                    },
                },
            ]);
    

    【讨论】:

      猜你喜欢
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      • 2016-01-03
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      相关资源
      最近更新 更多