Search code examples
mongodbmongodb-aggregation

Aggregate query with no $match


I have a collection in which unique documents from a different collection can appear over and over again (in example below item), depending on how much a user shares them. I want to create an aggregate query which finds the most shared documents. There is no $match necessary because I'm not matching a certain criteria, I'm just querying the most shared. Right now I have:

db.stories.aggregate(
    {
        $group: {
            _id:'item.id', 
            'item': { 
                $first: '$item'
            }, 
            'total': { 
                $sum: 1
            }
        }
    }
);

However this only returns 1 result. It occurs to me I might just need to do a simple find query, but I want the results aggregated, so that each result has the item and total is how many times it's appeared in the collection.

Example of a document in the stories collection:

{
    _id: ObjectId('...'),
    user: {
        id: ObjectId('...'),
        propertyA: ...,
        propertyB: ...,
        etc
    },
    item: {
        id: ObjectId('...'),
        propertyA: ...,
        propertyB: ...,
        etc
    }
}

users and items each have their own collections as well.


Solution

  • Change the line

    _id:'item.id'
    

    to

    _id:'$item.id' 
    

    Currently you group by the constant 'item.id' and therefore you only get one document as result.