Search code examples
node.jsmongodbaggregate-functions

MongoDB and Node.js aggregate using $sample isn't returning a document


I'm new to Nodejs and mongoDB and I'm trying to get an aggregate function running that will select a random document from the database and return it. I've looked all over on the internet to figure out what I'm doing wrong and from what I can see my code looks like it should. For some reason however, when I try printing the result to console, it gives me an aggregation cursor object and I can't find the document I want anywhere within it. Here is my code for the aggregate function.

//get a random question
route.get('/question/random', function (req, res) {
database.collection('questions').aggregate(
    [ { $sample: { size: 1} } ],
    function(err, result) {
        console.log(result);
    })
})

Solution

  • It's because aggregation method returns AggregationCursor that won't return any documents unless you iterate through it.

    For a simple iteration, you can do:

    database.collection('questions').aggregate([{$sample: {size: 1}}]).forEach(console.log);
    

    The forEach() method on the cursor will iterate it, and in this example will print it to the console.