简体   繁体   中英

Mongodb aggregate $count

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...

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)
  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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM