搜索

首页  >  问答  >  正文

去重 - MongoDB如何去除组合重复项

sql server有下列语句:

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

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

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

全部回复(3)我来回复

  • 某草草

    某草草2017-04-27 09:04:29

    雷雷

    回复
    0
  • 習慣沉默

    習慣沉默2017-04-27 09:04:29

    雷雷

    回复
    0
  • PHP中文网

    PHP中文网2017-04-27 09:04:29

    > 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/

    回复
    0
  • 取消回复