how to use mongodb aggregate and retrieve entire documents

后端 未结 5 2041
猫巷女王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:28
    db.collection.aggregate([
     {
    
      $group: {
       '_id':"$_id",
       'otherFields':{ $push: { fields: $ROOT } }
      } 
     }
    ])
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-11 11:32

    You should be using db.collection.find() rather than db.collection.aggregate():

    db.collection.find().sort({"created":-1}).limit(1)
    
    0 讨论(0)
  • 2021-01-11 11:49
    query = [
        {
            '$sort': {
                'created': -1
            }
        },
        {
            $group: { 
                '_id':null,
                'max':{'$first':"$$ROOT"}
            }
        }
    ]
    db.collection.aggregate(query)
    
    0 讨论(0)
  • 2021-01-11 11:50

    In the documentation i found that the $$ROOT expression addresses this problem.

    From the DOC: http://docs.mongodb.org/manual/reference/operator/aggregation/group/#group-documents-by-author

    0 讨论(0)
提交回复
热议问题