Search code examples
mongodbmongodb-querymongodb-javanosql

How to Find MongoDB Documents with the Same Value and Count Them?


In MongoDB, I need to use group aggregation (I believe), in order to get the number of documents in a collection with the same value. I need to get these results returned to me from greatest to least, and then get the common value for each result.

Eg.

  1. I have a normal query with a range (eg. field "value" > 5). I assume for this I should use the "match" feature when aggregating

  2. Get all documents with the same value for the "id" field, that also match the above query parameters

  3. Sort the results from most matching values to least

  4. Give me the common value of "id" for each result.

Sample documents:

    #1. Type: "Like", value: 6, id: 123
    #2. Type: "Like", value: 7, id: 123
    #3. Type: "Like", value: 7, id: 123
    #4. Type: "Like", value: 8, id: 12345
    #5. Type: "Like", value: 7, id: 12345
    #6. Type: "Like", value: 6, id: 1234
    #7. Type: "Like", value: 2, id: 1234
    #7. Type: "Like", value: 2, id: 1234
    #7. Type: "Like", value: 2, id: 1234

Expected output (assume I have a limit of 3 documents, and the query asks for only documents with the "value" field > 5):

1. id: 123
2. id: 12345
3. id: 1234

I expect these in this order, as the id 123 is most popular, and 1234 is least popular, of the documents where the "value" field > 5.

Ideally, I would have a method that would return something like a String[] of the resulting Ids, in order.


Solution

  • db.data.aggregate([
        {$match: {value:{$gt:5}}},
        {$group: {'_id':"$id", num:{$sum:1}, avg:{$avg:"$value"}}},
        {$sort:{num:-1}}, { $limit : 50}
    ])