Home > Blockchain >  Mongodb aggregate $count
Mongodb aggregate $count

Time:11-24

I would like to count the number of documents returned by an aggregation.

I'm sure my initial aggregation works, because I use it later in my programm. To do so I created a pipeline variable (here called pipelineTest, ask me if you want to see it in detail, but it's quite long, that's why I don't give the lines here).

To count the number of documents returned, I push my pipeline with : {$count: "totalCount"}

Now I would like to get (or log) totalCount value. What should I do ?

Here is the aggregation :

pipelineTest.push({$count: "totalCount"});
        cursorTest = collection.aggregate(pipelineTest, options)
        console.log(cursorTest.?)

Thanks for your help, I read lot and lot doc about aggregation and I still don't understand how to read the result of an aggregation...

CodePudding user response:

  1. Assuming you're using async/await syntax - you need to await on the result of the aggregation.
  2. You can convert the cursor to an array, get the first element of that array and access totalCount.
     pipelineTest.push({$count: "totalCount"});   
     cursorTest = await collection.aggregate(pipelineTest, options).toArray();  
     console.log(cursorTest[0].totalCount);

CodePudding user response:

Aggregation

db.mycollection.aggregate([
    {
        $count: "totalCount"
    }
])

Result

[ { totalCount: 3 } ]

Your Particulars

Try the following:

pipelineTest.push({$count: "totalCount"});
cursorTest = collection.aggregate(pipelineTest, options)
console.log(cursorTest.totalCount)
  • Related