我目前在使用NodeJS与$ sample实现聚合时遇到问题。
我想从MongoDB运行的查询是:
db.qmquestions.aggregate({$sample: {size: 1}})
将输出:
{ "_id" : ObjectId("58bf0f29b6942f2dd471b6cc"), "question" : { "questionTitle" : "Test", "question" : "What is the Capital of England", "answer" : "London" } }
我试图使用的代码是:
var generateQuestion = function(){
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost/quizmaster';
var results_from_mongo = [];
MongoClient.connect(url, function (err, db) {
var str = db.collection('qmquestions').find({}).toArray(function (err,docs){
//console.log(docs)
//for (var i = 0, len = docs.length; i < len; i++)
//{
var test = db.collection('qmquestions').aggregate(
{$sample: {size: 1}}
);
console.log(test)
//gameState.currentQuestion = docs[i].question.question
//console.log("currentQuestion is " + gameState.currentQuestion)
//}
return gameState.currentQuestion
})
});
};
但是从console.log返回的所有测试都是(这只是一个片段,因为它只是返回MongoDB服务器信息):
AggregationCursor {
pool: null,
server: null,
disconnectHandler:
Store {
s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: BSON {},
ns: 'quizmaster.qmquestions',
cmd:
{ aggregate: 'qmquestions',
pipeline: [ [Object] ],
cursor: { batchSize: 1000 } },
options:
{ readPreference: ReadPreference { preference: 'primary', tags: undefined, options: [Object] },
promiseLibrary: [Function: Promise],
cursorFactory: { [Function: AggregationCursor] super_: [Object], define: [Object], INIT: 0, OPEN: 1, CLOSED: 2 },
cursor: { batchSize: 1000 },
disconnectHandler: Store { s: [Object], length: [Getter] } },
如果有人能够发现我出错的地方会很好,因为我无法看到这个问题,我能想到的唯一一件事就是它不喜欢&中的聚合#34; var str&#34;调用
编辑: 我觉得我没有在我正在寻找的问题中得到我的问题,当调用generateQuestion函数来查看qmQuestions集合并从该集合中选择随机结果然后显示在测试变量中时。此功能调用按钮按下的形式,该形式未在问题中显示,与问题无关。每次调用函数时,随机结果都将放在测试变量中。
答案 0 :(得分:1)
您需要将管道表示为数组
试
var test = db.collection('qmquestions').aggregate([
{$sample: {size: 1}}
]);
答案 1 :(得分:0)
aggregate
函数返回一个cursor
。要从中获得价值,您必须对其进行迭代。
var test = db.collection('qmquestions').aggregate([
{$sample: {size: 1}}
]);
//iterate over test
await test.forEach(doc => console.log(doc)); //make your function async to use await
答案 2 :(得分:-1)
将结果转换为数组
var test = db.collection('qmquestions').aggregate(
{$sample: {size: 1}}
).toArray();