Distinct and group in MongoDB

2

I have this query:

db.getCollection('lojasDisponiveis').aggregate( [
  { $group: { _id:  { codigosLojas: "$codigosLojas", codigoUrl: "$codigoUrl" }}}
] );

The problem:

For each store or group of stores, I have a code that goes into a url parameter. However, some stores have different urls (different codes) that carry the same information (the same stores (171 and 232).

 {
    "_id": {
        "codigosLojas": [
            171, 232
        ],
        "codigoUrl": 676
    }
 }, {
    "_id": {
        "codigosLojas": [
            171, 232
        ],
        "codigoUrl": 675
    }
 }, {
    "_id": {
        "codigosLojas": [
            10
        ],
        "codigoUrl": 11
    }
 }, {
    "_id": {
        "codigosLojas": [
            21
        ],
        "codigoUrl": 2
    }
 }

In this example, the two urls with codes 676 and 675 have the same information. I need only one.

What I need:

If there are the same stores with different Url codes, bring only one set of information (from a url only). For example, this return:

 { "_id" : { "codigosLojas" : [ 171, 232 ], "codigoUrl" : 675 } }
 { "_id" : { "codigosLojas" : [ 10 ], "codigoUrl" : 11 } }
 { "_id" : { "codigosLojas" : [ 21 ], "codigoUrl" : 2 } }
    
asked by anonymous 27.12.2017 / 14:58

1 answer

1

You can only group by codigoUrl that will keep only one document:

db.getCollection('lojasDisponiveis').aggregate([{
    $group: {
        _id: "$codigoUrl",
        codigoUrl: { $first: "$codigoUrl" },
        codigosLojas: { $push: "$codigosLojas" }
    }
}]);
    
27.12.2017 / 15:10