在 MongoDB 中聚合不同的值 [英] Aggregate distinct values in MongoDB

查看:39
本文介绍了在 MongoDB 中聚合不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 18625 个集合的 mongodb 数据库.它有以下键:

I have a mongodb db with 18625 collections. It has following keys:

    "_id" : ObjectId("5aab14d2fc08b46adb79d99c"), 
    "game_id" : NumberInt(4), 
    "score_phrase" : "Great", 
    "title" : "NHL 13", 
    "url" : "/games/nhl-13/ps3-128181", 
    "platform" : "PlayStation 3", 
    "score" : 8.5, 
    "genre" : "Sports", 
    "editors_choice" : "N", 
    "release_year" : NumberInt(2012), 
    "release_month" : NumberInt(9), 
    "release_day" : NumberInt(11)

现在,我希望创建仅包含流派的另一个维度/集合.

Now, i wish to create another dimension/ collection with only genres.

如果我使用以下查询:

db.ign.aggregate([ {$project: {"genre":1}}, { $out: "dimen_genre" } ]);

它生成了 18625 个集合,即使只有 113 个不同的集合类型.

It generates 18625 collections, even though there are only 113 distinct genres.

如何在此处应用 distinct 并获取仅具有不同 113 个值的流派的集合.我用谷歌搜索,它表明聚合和不同在 mongo 中不能一起工作.我也试过:db.dimen_genre.distinct('genre').length这表明在维度_流派中,有 113 个不同的流派.

How to apply distinct here and get the collection for genres with only the distinct 113 values. I googled, bt it showed that aggregate and distinct don't work together in mongo. I also tried : db.dimen_genre.distinct('genre').length this showed that in dimension_genre, there are 113 distinct genres.

确切地说,如何从只有不同值的现有集合中创建集合.

Precisely, how to make a collection from existing one with only distinct values.

我对 NoSQL 非常陌生.

I am really new to NoSQLs.

推荐答案

您可以使用 $addToSet 将唯一值分组到一个文档中,然后 $unwind 取回多个文档:

You can use $addToSet to group unique values in one document and then $unwind to get back multiple docs:

db.ign.aggregate([
    {
        $group: {
            _id: null,
            genre: { $addToSet: "$genre" }
        }
    },
    {
        $unwind: "$genre"
    },
    {
        $project: {
            _id: 0
        }
    },
    { $out: "dimen_genre" }
]);

这篇关于在 MongoDB 中聚合不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆