Teemo
Teemo

Reputation: 35

Find field in collection based off another collection

There are currently 2 collections that I am trying to work with. One is the Questions collection and the other is the Answers collection. The documents within the Questions collection contains the tags for each Question. How would I go about finding the number of answers under each tag when the answer documents do not contain the tags field?

db.collection.distinct("tags:") is what I have to find the tags in the Questions collection

Questions Sample:

_id: ObjectId("5a7c8c30f1557ea7894e553d")
title:"Incididunt dolore laboris ut officia nisi."
tags: Array
body:"Lorem deserunt cillum aliqua fugiat. Qui sit veniam voluptate aliqui"
author:"testAuthor"
votes:Array
status:"UNANSWERED"
time:1277144388539

Answer Sample:

 "_id":"5a7c8ffcd117b014dc0c0e25",
 "body":"asalkdjalksjlkdjsaljdas",
 "author":"testAuthor",
 "time":"1518112764502",
 "accepted":false,
 "votes":[],
 "question":"ObjectId(5a7c8d0ad117b00d6492211d)"

Upvotes: 0

Views: 274

Answers (1)

mickl
mickl

Reputation: 49945

You can try following aggregation:

db.Questions.aggregate([
    {
        $lookup: {
            from: "Answers",
            localField: "_id",
            foreignField: "question",
            as: "answers"
       }
    },
    {
        $project: {
            tags: 1,
            total_answers: { $size: "$answers" }
        }
    },
    {
        $unwind: "$tags"
    },
    {
        $group: {
            _id: "$tags",
            total: { $sum: "$total_answers" }
        }
    }
])

$lookup simply inserts an array of matching documents from another collection. Then we can count all the answers per question ($size returns a length of an array). To $group by tags we need to $unwind them earlier.

Upvotes: 1

Related Questions