MongoDB中distinct的详细用法

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


语法:

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”})   //满足deptA数据的item字段的子字段的不重复值

 

结果:[“111”,”333”]

 

 

 

 

  • 7
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值