how to use mongodb aggregate and retrieve entire documents

后端 未结 5 2040
猫巷女王i
猫巷女王i 2021-01-11 10:53

I am seriously baffled by mongodb\'s aggregate function. All I want is to find the newest document in my collection. Let\'s say each record has a field \"created\"



        
5条回答
  •  离开以前
    2021-01-11 11:29

    I think I figured it out. For example, I have a collection containing an array of images (or pointers). Now I want to find the document with the most images

    results=[];
    db.collection.aggregate([
        {$unwind: "$images"},
        {$group:{_id:"$_id", 'imagecount':{$sum:1}}},
        {$group:{_id:"$_id",'max':{$max: "$imagecount"}}},
        {$sort:{max:-1}},
        {$group:{_id:0,'id':{$first:'$_id'},'max':{$first:"$max"}}}
    ]).result.forEach(function(d){
        results.push(db.stories.findOne({_id:d.id}));
    });
    

    now the final array will contain the document with the most images. Since images is an array, I use $unwind, I then group by document id and $sum:1, pipe that into a $group that finds the max, pipe it into reverse $sort for max and $group out the first result. Finally I fetchOne the document and push it into the results array.

提交回复
热议问题