mongodb中使用distinct去重的簡單方法

怎麼在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 ]

以上所述就是本文的全部內容了,希望大家能夠喜歡。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章