简体   繁体   中英

Mongodb: How to get the count of documents in different collections using one query?

How can I get the count of documents in different collections using one query?

Assume I have three collections: 1. Users, 2. Posts, 3. Chatrooms.

I want to create a query that returns:

 the total number of users, total number of posts and total number of
 chatrooms

Is it possible to do this in one MongoDB query? It does not matter if the solution uses aggregation or not. Any working solution would be great.

You can do it using aggregation like below:

db.Users.aggregate([
    /** After this stage there will be only one document with one count field, till following `lookup` stage */
    {
      $count: "TotalUsers"
    },
    /** lookup on 'Posts' collection without any conditions & just count docs, After this stage there will be only one doc with two fields */
    {
      $lookup: {
        from: "Posts",
        pipeline: [ { $count: "TotalPosts" }],
        as: "posts"
      }
    },
    /** lookup on 'Chatrooms' collection without any conditions & just count docs, After this stage there will be only one doc with three fields */
    {
      $lookup: {
        from: "Chatrooms",
        pipeline: [ { $count: "TotalChatrooms" } ],
        as: "Chatrooms"
      }
    },
    /** Transform the fields as like we wanted,
     * if a collection is empty you won't see that particular field in response, easy to handle it in code */
    {
      $project: {
        TotalUsers: 1,
        TotalChatrooms: { $arrayElemAt: [ "$Chatrooms.TotalChatrooms", 0 ] },
        TotalPosts: { $arrayElemAt: [ "$posts.TotalPosts", 0 ] }
      }
    }
  ])

Test: mongoplayground

Ref: aggregation-pipeline

Note: Here we've used specify-multiple-join-conditions-with-lookup stage without any conditions & with just $count . I believe this query might be fast enough. If possible I would prefer going on a route where you can execute .count() on all 3 collections in parallel. But as you wish to get it done in one query you can use above aggregation pipeline, Just in case if you wanted to check performance of query try to use $explain .

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