How to count $lookup data

I have two collections, users and versions. Here is a sample of the version collection

{
    "_id": {
        "$oid": "6013838305cbb735a07481be"
    },
    "schemaVersion": "1.0.0",
    "releaseType": "Stable",
    "version": "0.6.2",
    "createdAt": "2021-01-14T21:34:39.838Z",
    "updatedAt": {
        "$date": "2021-09-14T02:59:57.605Z"
    },
    "availability": "discontinue",
    "default": false
}

Here is a record from the users that references the version collection.

{
    "_id": {
        "$oid": "6068b22556a8375b842af8e4"
    },
    "server": {
        "licenseValid": true,
        "allowedStart": true,
        "restorePoint": {
            "$date": "2022-09-29T19:33:16.889Z"
        },
        "licenseKey": "DEMO ACCOUNT",
        "releaseVersion": {
            "$oid": "6013838305cbb735a07481be"
        }
    },
   
}

I am trying to create an aggregation that the end result looks like:

{
 version: "0.6.2",
 count: 1
}

I want to query all the versions and then count how many users are using that version. I have tried all kinds of permutations and just can’t seem to get it. In the old mysql days… this was pretty easy. Any help would be greatly appreciated.

Did you try anything?

From the text, it seems you will need:

  • $lookup stage
  • $group using as id the version, while summing up one on each match

This wont get just one but all the versions.

I think it will benefit you to try and share it. Use https://mongoplayground.net if you like.

1 Like