简体   繁体   中英

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. I tried {quiz.score} and {quiz:{$elemMatch:{score:1}}} but both return 0 length or without values.

I need the questionId for only the documents with a score of 1.

Mongoose Schema

quiz: {
    type: Array,
    questionId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Question',
        index: true
    },
    score: { type: Number },
    time: { type: String }
}   

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

"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}};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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