去重 - MongoDB如何去除组合重复项
高洛峰
高洛峰 2017-04-27 09:02:29
0
3
1113
sql server有下列语句:

// 查找名字性别唯一的学生
select distinct name,sex from student

// 转换成MongoDB的话,我怎么把这种组合列去重,MongoDB好像只支持单个field的去重
db.student.distinct("name"); // 只支持一个field
db.student.distinct("name","sex"); // 错误的,不支持多个field的组合去重

有没有大神解决过类似问题,求指导.................
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(3)
某草草

雷雷

習慣沉默

雷雷

洪涛
> db.test.find()
{ "_id" : ObjectId("55de6075024f45b4947d4cc3"), "name" : "zhangsan", "sex" : "FEMALE", "age" : 12 }
{ "_id" : ObjectId("55de6076024f45b4947d4cc4"), "name" : "zhangsan", "sex" : "MALE", "age" : 16 }
{ "_id" : ObjectId("55de6076024f45b4947d4cc5"), "name" : "lisi", "sex" : "FEMALE", "age" : 20 }
{ "_id" : ObjectId("55de6076024f45b4947d4cc6"), "name" : "zhangsan", "sex" : "FEMALE", "age" : 25 }
{ "_id" : ObjectId("55de6076024f45b4947d4cc7"), "name" : "lisi", "sex" : "FEMALE", "age" : 36 }
{ "_id" : ObjectId("55de6077024f45b4947d4cc8"), "name" : "zhangsan", "sex" : "FEMALE", "age" : 28 }
> db.test.aggregate([
...     { $group: { _id: { name: "$name", sex: "$sex" } } }
... ])
{ "_id" : { "name" : "lisi", "sex" : "FEMALE" } }
{ "_id" : { "name" : "zhangsan", "sex" : "MALE" } }
{ "_id" : { "name" : "zhangsan", "sex" : "FEMALE" } }
> db.test.distinct("name");
[ "zhangsan", "lisi" ]
> db.test.distinct("name","sex");
[ "zhangsan", "lisi" ]
> db.test.distinct("name","sex","age");
[ "zhangsan", "lisi" ]

楼上的方法是正确的,mongoDB确实不支持组合去重,mongo官网提供的示例也只是对单个字段去重。

官网示例: http://docs.mongodb.org/manual/core/single-purpose-aggregation/

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板