您的位置:首页 > 博客中心 > 数据库 >

mongodb distinct去重

时间:2022-03-13 23:48

  MongoDB的destinct命令是获取特定字段中不同值列表。该命令适用于普通字段,数组字段和数组内嵌文档.

mongodb的distinct的语句:

db.users.distinct(‘last_name‘)

等同于 SQL 语句:

select DISTINCT last_name from users

表示的是根据指定的字段返回不同的记录集。

一个简单的实例:

gxlsystem.com,布布扣gxlsystem.com,布布扣
// 
gxlsystem.com,布布扣
> db.addresses.insert({"zip-code": 10010}) 
gxlsystem.com,布布扣
> db.addresses.insert({"zip-code": 10010}) 
gxlsystem.com,布布扣
> db.addresses.insert({"zip-code": 99701}) 
gxlsystem.com,布布扣gxlsystem.com,布布扣
> // shell helper: 
gxlsystem.com,布布扣
> db.addresses.distinct("zip-code"); 
gxlsystem.com,布布扣
[ 10010, 99701 ] 
gxlsystem.com,布布扣gxlsystem.com,布布扣
> // running as a command manually: 
gxlsystem.com,布布扣
> db.runCommand( { distinct: ‘addresses‘, key: ‘zip-code‘ } ) 
gxlsystem.com,布布扣
{ "values" : [ 10010, 99701 ], "ok" 
gxlsystem.com,布布扣
// 
gxlsystem.com,布布扣
> db.comments.save({"user": {"points": 25}}) 
gxlsystem.com,布布扣
> db.comments.save({"user": {"points": 31}}) 
gxlsystem.com,布布扣
> db.comments.save({"user": {"points": 25}}) 
gxlsystem.com,布布扣gxlsystem.com,布布扣
> db.comments.distinct("user.points"); 
gxlsystem.com,布布扣
[ 25, 31 ]

热门排行

今日推荐

热门手游