【问题标题】:Duplicates in aggregation with $addToSet与 $addToSet 聚合重复
【发布时间】:2014-09-05 14:37:19
【问题描述】:

我对 MongoDB 中的聚合框架相当陌生,但据我了解,$addToSet 功能仅向数组添加唯一值并忽略现有值。所以由于某种原因,下面的聚合仍然会产生重复

db.tweets.aggregate([
{ 
    $group: { 
        _id: "$_id",
        hashtags: { 
            $addToSet : "$tweet.entities.hashtags.text" 
        }
    }
},
{ $unwind : "$hashtags" }
]);

原始标签数组:

"hashtags" : [
                {
                    "indices" : [
                        64,
                        73
                    ],
                    "text" : "TONYTour"
                },
                {
                    "indices" : [
                        97,
                        101
                    ],
                    "text" : "NIU"
                },
                {
                    "indices" : [
                        102,
                        106
                    ],
                    "text" : "NIU"
                },
                {
                    "indices" : [
                        107,
                        111
                    ],
                    "text" : "NIU"
                }
            ]
        },

结果:

{
        "_id" : ObjectId("53f4aad7485aee023d000115"),
        "hashtags" : [
            "TONYTour",
            "NIU",
            "NIU",
            "NIU"
        ]
    }

我尝试在放松后做第二组,但没有成功。那么,为了实现我正在寻找的结果,我究竟没有从聚合框架中掌握什么:

{
        "_id" : ObjectId("53f4aad7485aee023d000115"),
        "hashtags" : [
            "TONYTour",
            "NIU"
        ]
    }

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    我猜你的问题是documentation的这一部分

    $addToSet 仅确保没有重复项添加到 设置并且不影响现有的重复元素。 $addToSet 确实 不保证修改集中元素的特定顺序。

    所以你的问题是,重复的 hastags 在同一个文档中。您可以先使用unwind 来解决这个问题:

    db.tweets.aggregate([
    { 
    
       { $unwind : "$tweet.entities.hashtags" },
        $group: { 
            _id: "$_id",
            hashtags: { 
                $addToSet : "$tweet.entities.hashtags.text" 
            }
        }
    }
    ]);
    

    这将为每个主题标签创建一个文档,然后$addToSet 不应添加重复项

    编辑:Neil Lunn 更正

    【讨论】:

    • 请注意,来源在“$tweet.entities.hashtags”中,而不是在“$hashtags”中。
    • 更正了。谢谢
    猜你喜欢
    • 2017-01-31
    • 1970-01-01
    • 2014-03-24
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多