MongoDB 数据库 — 实例总结

本篇打算总结一些碰到的实例,后面碰到问题再进行补充。

实例1:aggregate 实现 count(distinct field)

我们知道在 SQL 中,要实现这样的功能,只需要 count(distinct field) 即可,虽然 MongoDB 中有聚合函数 count,distinct,但是,在 aggregate 聚合管道操作中却没有这样的用法,因此,需要使用其它方法来实现这种功能。

1 聚合函数 count 和 distinct

# count 聚合函数
db.collection.count(<query>)

#或者
db.collection.find(<query>).count()

# distinct 聚合函数
db.collection.distinct(field, query)

# 例如
db.collection.distinct('user', {'age': {'$gt': 28}});  //用于查询年龄age大于28岁的不同用户名

2 aggregate 管道操作中实现 count(distinct field) 功能

对集合中每个 account 使用的不同 vendor 个数计数

# 文档内容
{
    { _id: 1,
     account: 'abc',
     vendor: 'amazon'
    },

    { _id: 2,
     account: 'abc',
     vendor: 'overstock'
    },

    { _id: 3,
     account: 'adf',
     vendor: 'amazon'
    }
}

# 统计方法
db.collection.aggregate([
                { '$group': { '_id': { 'account': '$account', 'vendor': '$vendor'} },
                  'number': { '$sum': 1 }                                        
                },
                { '$group': { '_id': '$_id.account' },
                  'number': { '$sum': 1 }
                }
    ])

# 结果
[ 
    { '_id': 'abc', 'number': 2 },
    { '_id': 'adf', 'number': 1 }
]

参考资料

MongoDB Aggregation: Counting distinct fields

posted @ 2019-06-28 10:19  Hiidiot  阅读(987)  评论(1编辑  收藏  举报