Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use mongodb aggregate and retrieve entire documents

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"

db.collection.aggregate({
    $group: { 
        _id:0,
        'id':{$first:"$_id"},
        'max':{$max:"$created"}
    }
})

yields the correct result, but I want the entire document in the result? How would I do that?

This is the structure of the document:

{
    "_id" : ObjectId("52310da847cf343c8c000093"),
    "created" : 1389073358,
    "image" : ObjectId("52cb93dd47cf348786d63af2"),
    "images" : [
        ObjectId("52cb93dd47cf348786d63af2"),
        ObjectId("52f67c8447cf343509d63af2")
        ],
    "organization" : ObjectId("522949d347cf3402c3000001"),
    "published" : 1392601521,
    "status" : "PUBLISHED",
    "tags" : [ ],
    "updated" : 1392601521,
    "user_id" : ObjectId("52214ce847cf344902000000")
}
like image 449
Jamgold Avatar asked Mar 12 '14 17:03

Jamgold


People also ask

How do I fetch all documents in MongoDB?

Connect to a database using the getDatabase() method. Get the object of the collection from which you want to retrieve the documents, using the getCollection() method. Retrieve the iterable object containing all the documents of the current collection by invoking the find() method.

Which aggregation method is preferred for use by MongoDB?

The pipeline provides efficient data aggregation using native operations within MongoDB, and is the preferred method for data aggregation in MongoDB. The aggregation pipeline can operate on a sharded collection. The aggregation pipeline can use indexes to improve its performance during some of its stages.

What does MongoDB aggregation return?

aggregate() method returns a cursor to the documents produced by the final stage of the aggregation pipeline operation, or if you include the explain option, the document that provides details on the processing of the aggregation operation.

How do you do aggregate queries in MongoDB?

In MongoDB, aggregation operations process the data records/documents and return computed results. It collects values from various documents and groups them together and then performs different types of operations on that grouped data like sum, average, minimum, maximum, etc to return a computed result.


2 Answers

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

like image 93
Volox Avatar answered Sep 29 '22 17:09

Volox


query = [
    {
        '$sort': {
            'created': -1
        }
    },
    {
        $group: { 
            '_id':null,
            'max':{'$first':"$$ROOT"}
        }
    }
]
db.collection.aggregate(query)
like image 23
Vijay Karthik P Avatar answered Sep 29 '22 17:09

Vijay Karthik P