这篇文章主要介绍mongodb执行distinct的方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

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

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

语法:

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

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

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

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

MongoDB的distinct的语句:

代码如下:

db.users.distinct('last_name')

等同于 SQL 语句:

代码如下:

selectDISTINCTlast_namefromusers

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

一个简单的实例:

//>db.addresses.insert({"zip-code":10010})>db.addresses.insert({"zip-code":10010})>db.addresses.insert({"zip-code":99701})>//shellhelper:>db.addresses.distinct("zip-code");[10010,99701]>//runningasacommandmanually:>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]

以上是mongodb执行distinct的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!