Home > Mobile >  Mongoose - How to get unique data based on some fields using aggregation
Mongoose - How to get unique data based on some fields using aggregation

Time:01-15

I have these fields in the document,

doc: {
    "id": "632ac8cba7723378033fef10",
    "question": 1,
    "text": "aasdfghjk,mnbvcxswertyuikmnbvcxsrtyuiknbvcdrtyujnbvcddtyjnbvfty",
    "slug": "xcvbnrddfghjktdxjjydcvbyrsxcvbhytrsxggvbjkytrdgc",
    "subject": 25866,
    "tutorInfo": {
        "tutorId": "632ac8cba7723378033fa0fe",
        "tutorIncrementalId": 95947
    }
}

the same tutorInfo can Occur in multiple documents.

const allQuestionBySubject = await QuestionParts.aggregate([
    {
        $match: {
            $and: [
                {
                    subject: subjectIncrementalId 
                },
                {tutorInfo: {$exists: true}}
            ]
        }
    },


    { "$skip": page * limit },
    { "$limit": limit },


    {
        $lookup: {
            from: "profiles",
            localField: "tutorInfo.tutorIncrementalId",
            foreignField: "incrementalId",
            as: "tutorDetails"
        }
    }
])

Code to get a list of questions as per subject.

I am filtering documents based on subject and as I mentioned the same tutorInfo can be present in multiple documents so in the result same tutor can be present in multiple documents, How can I get a unique list of documents in which tutorInfo shouldn't be repeated.

CodePudding user response:

Since the same tutorInfo is present in multiple records, You can use $group to group the document on the tutorInfo.tutorId field.

const allQuestionBySubject = await QuestionParts.aggregate(
    [
        {
            $match: {
                $and: [
                    {
                        subject: subjectIncrementalId
                    },
                    { tutorInfo: { $exists: true } }
                ]
            }
        },


        { "$skip": page * limit },
        { "$limit": limit },

        {
            "$group": {
                _id: "$tutorInfo.tutorId",
                question: { $first: "$question" },
                text: { $first: "$text" },
                slug: { $first: "$slug" },
                subject: { $first: "$orderId" },
                tutorInfo: { $first: "$tutorInfo" },
            }
        },

        {
            $lookup: {
                from: "profiles",
                localField: "tutorInfo.tutorIncrementalId",
                foreignField: "incrementalId",
                as: "tutorDetails"
            }
        }
    ]
)
  • Related