Distinct and group in Mongodb

Asked

Viewed 75 times

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 in a url parameter. However, some stores have different urls (different codes) that bring 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 bring the same information. I need only one.

What I need:

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

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

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" }
    }
}]);
  • Hi Lucas!! I edited the question, it was not clear. It would not only bring a result of the entire Collection, but rather all the results, in the case of "duplicate" stores, bring only one.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.