SGR Dalal
SGR Dalal

Reputation: 121

Get total count from another collection using first collection id

I am having two collections.

First one id pods having following structure:

{
    "_id": "5ae46c0aff1bde1634ad8b3f",
    "admin": "595bdd5aa6ea2811d48a7802",
    "name": "Fashion Trend",
    "datetime": 1524919038771,
    "approval": false,
    "actions": "Comments",
    "description": "Fashion is about dressing according to what's fashionable. Style is more about being yourself.",
    "profilepic": "https://cdn.com/upload/Community_photos/595bdd5aa6ea2811d48a7802_1524919188491.jpg",
    "coverpic": "https://cdn.com/upload/Community_photos/595bdd5aa6ea2811d48a7802_1524919171374.jpg",
    "__v": 0
}

second is pod_members and structure is as followed:

{
    "_id": "5b127683187a4f19901e34b7",
    "__v": 0,
    "pod_id": "5ae470d04e15d607f043a20e",
    "instaid": "5ad9a44cabd2180d64073462",
    "username": "tagtor",
    "user_id": "595bdd5aa6ea2811d48a7802",
    "member_name": "Sagar Dalal",
    "req_date": 1527936643123,
    "datetime": 1527938142745,
    "comments": ["Love the page. 👏 🙏 👍 keep up the good job.", "Great job done with this page.👌", "Fabulous. 👏 🙏  👌👍", "Keep up the great job. Well done.👌👏 🙏 👍", "Amazing instagram page. 👏 👌👍"]
}

I need total_members for each pod also if pod dose not have any member result should return 0 on behalf.

My Query is like:

Pod.aggregate([
    {
        $lookup: {
            from: "pod_members",
            localField: "_id",
            foreignField: "pod_id",
            as: "meminfo"
        }
    },
    { $unwind: "$meminfo" },
    {
        $group: {
            _id: "meminfo.pod_id",
            total_members: { $sum: 1 }
        }
    },
    { $addFields: { "Status": false } }
]).exec(function (err, resp) {
    if (err) console.log(err)
    else console.log(resp)
}) 

But its not giving me desired result.

I need result Like:

[{ _id: 5ae46c0aff1bde1634ad8b3f,
    admin: 595bdd5aa6ea2811d48a7802,
    name: 'Fashion Trend',
    datetime: 1524919038771,
    approval: false,
    actions: 'Comments',
    description: 'Fashion is about dressing according to what\'s fashionable. Style is more about being yourself.',
    profilepic: 'https://cdn.com/upload/Community_photos/595bdd5aa6ea2811d48a7802_1524919188491.jpg',
    coverpic: 'https://cdn.com/upload/Community_photos/595bdd5aa6ea2811d48a7802_1524919171374.jpg',
    __v: 0,
    total_members: 1,
    Status: false }]

Upvotes: 1

Views: 764

Answers (1)

s7vr
s7vr

Reputation: 75924

I would change your aggregation a little bit so you don't need to use $group stage. Use $size to get the total_members instead of $sum. Replace stages after $lookup with below stages.

{"$addFields":{
  "total_members":{
    "$size":{
      "$filter":{
        "input":"$meminfo",
        "as":"mi",
        "cond":{"$gt":["$$mi.datetime",null]}
      }
    }
  }
}},
{"$project":{"meminfo":0}},
{"$addFields":{"Status":false}}

Upvotes: 2

Related Questions