您的位置:首页 > 数据库 > Mongodb

MongoDB中distinct的详细用法

2017-02-18 15:41 453 查看
作用:获取集合中指定字段的不重复值,并以数组的形式返回

语法:

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

 

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

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

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

 

options

 

 
{ collation: <document> }
 
collation: {
   locale: <string>,
   caseLevel: <boolean>,
   caseFirst: <string>,
   strength: <int>,
   numericOrdering: <boolean>,
   alternate: <string>,
   maxVariable: <string>,
   backwards: <boolean>
}
 
 

 

例如:

如下是 inventory 集合的数据

{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] }
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }
 

>  db.inventory.distinct(“dept”)  //获取dept字段的不重复值
 
结果:[“A”,”B”]
 
 

 

> db.inventory.distinct(“item.sku”)   //获取item子字段sku的不重复值
 
  结果:[“111”,”222”,”333”]
 
 

>db.inventory.distinct(“sizes”)       //获取数组格式字段的不重复值
  
      结果:[“M”,”S”,”L”]
 
 

 

>db.inventory.distinct(“item.sku”,{dept:”A”})   //满足dept为A数据的item字段的子字段的不重复值
 
结果:[“111”,”333”]
 
 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: