mongodb中使用distinct去重的簡單方法
更新時間:2015年05月12日 10:11:32 投稿:hebedich
怎么在mongodb中實現類似于SQL中distinct的功能,查詢某一個字段所有的值,今天我們就來探討下這個問題。
MongoDB的destinct命令是獲取特定字段中不同值列表。該命令適用于普通字段,數組字段和數組內嵌文檔.
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 ]
以上所述就是本文的全部內容了,希望大家能夠喜歡。
您可能感興趣的文章:

