问题描述
sql server有下列语句:// 查找名字性别唯一的学生select distinct name,sex from student// 转换成MongoDB的话,我怎么把这种组合列去重,MongoDB好像只支持单个field的去重db.student.distinct('name'); // 只支持一个fielddb.student.distinct('name','sex'); // 错误的,不支持多个field的组合去重有没有大神解决过类似问题,求指导.................
问题解答
回答1:恩。这个方法试过了。根据id分组,id指定为组合项的话,因为id不会重复,所以作用相当于把组合项去重了。我给你们补充下:假如现在需要拿出collection的其他field的话,可以使用$push关键字 // 根据name和sex分组 // 把分组后的name,sex,age放到对应的Document下,形成一个数组 db.student.aggregate( [ {$group:{ _id: {name: '$name', sex: '$sex'}, name: {$push: '$name'}, sex: {$push: '$sex'}, age: {$push: '$age'}} } ]). forEach(function(x){ db.temp.insert( { name: x.name, sex : x.sex, age: x.age } );});回答2:
collection = db.tb;result = collection.aggregate( [{'$group': { '_id': { market: '$market', code: '$code' } } } ]);printjson(result);回答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/