Search code examples
mongodbexpressmongoosemongoose-schema

Get count number from mongoDB


I'm creating questions and answers web site using mango and express.So there are two schema for Question and Answer.

My Question and Answer Schema like this,

const questionSchema = mongoose.Schema({
_id : mongoose.Schema.Types.ObjectId,
user: { type:mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
title: {type: String , required:true},
question: {type: String , required:true},
tags: {type: Array , required: true},
time : { type : Date, default: Date.now },
vote: {type: Number, default: 0},
views: {type: Number, default: 0}     });


const answerSchema = mongoose.Schema({
_id : mongoose.Schema.Types.ObjectId,
user: { type:mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
question:{ type:mongoose.Schema.Types.ObjectId, ref: 'Question', required: true},
comment: [{type: mongoose.Schema.Types.ObjectId, ref: 'Comment', default: null }],
answer: {type: String, required: true},
vote: {type: Number , default: 0},
time : { type : Date, default: Date.now }   });

In here there are many answers related to the one question.My home page get the all questions to preview.How to get the count number of answers related to the each question?


Solution

  • Since your questionSchema doesn't have any direct relation with Answers collection (like doesn't store Answers reference) then try this :

    Query :

    db.Question.aggregate([
        {
            $lookup:
            {
                from: "Answer",
                localField: "_id",
                foreignField: "question",
                as: "answers"
            }
        }, 
        /** In case if you need all details of question replace 'project' with 'addFields' & remove 'question: 1' */
        { $project: { question: 1, count: { $size: '$answers' } } } 
    ])
    

    Test : MongoDB-Playground