简体   繁体   English

使用$ sample的MongoDB和Node.js聚合未返回文档

[英]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. 我是Nodejs和mongoDB的新手,我正在尝试运行一个聚合函数,该函数将从数据库中选择一个随机文档并返回它。 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);
    })
})

It's because aggregation method returns AggregationCursor that won't return any documents unless you iterate through it. 这是因为聚合方法返回的AggregationCursor除非您对其进行迭代,否则不会返回任何文档。

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. 光标上的forEach()方法将对其进行迭代,并且在此示例中,将其打印到控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM