Mike_Device
Mike_Device

Reputation: 672

Console log in MongoDB Shell

I want to write functions into MongoDB Shell like this:

var last = function(collection) { db[collection].find().sort({_id: -1}).limit(1).toArray(); }

But there is one problem. When I call last() function, it will make no output. How to fix it?

Upvotes: 0

Views: 1334

Answers (1)

chridam
chridam

Reputation: 103455

You need to use either use the JavaScript print() function or the mongo specific printjson() function which returns formatted JSON to actually log to output the result from the find method, for example:

var last = function(collection) { 
    var doc = db.getCollection(collection).find().sort({_id: -1}).limit(1).toArray(); 
    printjson(doc); 
};
last("test");

Upvotes: 2

Related Questions