ITPub博客

首页 > IT职业 > IT生活 > mongodb如何执行distinct

mongodb如何执行distinct

IT生活 作者:nicole1108 时间:2021-09-11 10:25:13 0 删除 编辑

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

作用:获取集合中指定字段的不重复值,并以数组的形式返回。

语法:

db.collection_name.distinct(field,query,options)

·field -----指定要返回的字段(string)

·query-----条件查询(document)

·options-----其他的选项(document)

MongoDB的distinct的语句:

代码如下:

db.users.distinct('last_name')

等同于 SQL 语句:

代码如下:

select DISTINCT last_name from users

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

一个简单的实例:

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

python学习网,大量的免费MongoDB入门教程,欢迎在线学习!

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2950/viewspace-2835124/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-06

  • 博文量
    79
  • 访问量
    573