[英]How we query array elements in node js for mongodb
I'm using the Mongoose library in nodejs with the query below but I'm not getting any documents back. 我正在使用nodejs在下面的查询中的Mongoose库,但没有得到任何文档。 I tried {quiz.score}
and {quiz:{$elemMatch:{score:1}}}
but both return 0 length or without values. 我尝试了{quiz.score}
和{quiz:{$elemMatch:{score:1}}}
但是都返回0长度或没有值。
I need the questionId for only the documents with a score of 1. 我只需要得分为1的文档的questionId。
Mongoose Schema 猫鼬模式
quiz: {
type: Array,
questionId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Question',
index: true
},
score: { type: Number },
time: { type: String }
}
Nodejs Nodejs的
function(){
var query = {
"quiz.score": 1
};
var select = 'quiz';
quizChild.find({
quiz:{
$elemMatch:{
score:1
}
}
}, select, function(err, attempquestion){
var att = attempquestion[0].quiz.length;
for(var i=0;i<att;i++){
var id = attempquestion[0].quiz[i].questionId;
console.log(id);
}
});
}
MongoDB documents MongoDB文件
"quiz" : [
{
"time" : "2016-09-02T17:26:07.109Z",
"score" : "1",
"questionId" : "57c14a36b78cd543fc59b81d"
},
{
"questionId" : "57c14a36b78cd543fc59b81e",
"score" : "0",
"time" : "2016-09-02T17:29:33.699Z"
},
{
"questionId" : "57c14a36b78cd543fc59b81f",
"score" : "1",
"time" : "2016-09-02T17:31:56.329Z"
},
{
"questionId" : "57c14a36b78cd543fc59b81f",
"score" : "1",
"time" : "2016-09-02T17:31:56.345Z"
},
{
"questionId" : "57c14a36b78cd543fc59b820",
"score" : "1",
"time" : "2016-09-02T17:32:14.699Z"
},
{
"questionId" : "57c14a36b78cd543fc59b821",
"score" : "0",
"time" : "2016-09-02T17:32:30.754Z"
}
change your query to 将您的查询更改为
var query = {"quiz.score":1, "quiz.score":1};
//or
var query = {"quiz.score":1, $eq:{"quiz.score":1}};
//greater than one
var query = {"quiz.score":1, $gt: {"quiz.score":1}};
//lesser than one
var query = {"quiz.score":1, $lt:{"quiz.score":1}};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.