suchen

Heim  >  Fragen und Antworten  >  Hauptteil

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

sql server有下列语句:

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

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

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

Antworte allen(3)Ich werde antworten

  • 某草草

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

    恩。这个方法试过了。
    根据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
                      }
                );
            });

    Antwort
    0
  • 習慣沉默

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

    collection = db.tb;
    result = collection.aggregate( 
                [
                    {"$group": { "_id": { market: "$market", code: "$code" } } }
                ]
            );
    printjson(result);

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

    Antwort
    0
  • StornierenAntwort