skip to Main Content

I have two collections Posts an comments. I am storing comments with postID. I want to show comments count field when fetching all the posts data.
How do I achieve this?


    // posts
    {
        postID: '123',
        title: 'abc'
    }

    // comments 
    {
         postID: '123',
         comments: [
            {
                commentID: 'comment123',
                comment: 'my Comment'
            }
         ]
    }

    // Looking for this
    {
        postID: '123',
        title: 'abc',
        commentCount: 1
    }

2

Answers


  1. Try This.

    pipeline = [{
        "$lookup": {
            "from": "comments",
            "let": {
                "postId": "$postId",
            },
            "pipeline": [
                {
                    "$match": {
                        "$expr": {
                            "$eq": ["$postId", "$$postId"]
                        },
                    }
                },
                {
                    "$group": {
                        "_id": "$postId",
                        "comments_count": {"$sum": 1}
                    }
                }
            ],
            "as": "comments"
        }
    },
    {
        "$project": {
            "_id": 0,
            "postId": 1,
            "title":1,
            "comments_count": "$comments.comments_count"
        }
    }]
    
    db.posts.aggregate(pipeline)
    
    Login or Signup to reply.
  2. Here’s one way you could do it.

    db.posts.aggregate([
      {
        "$lookup": {
          "from": "comments",
          "localField": "postID",
          "foreignField": "postID",
          "pipeline": [
            {
              "$project": {
                "_id": 0,
                "commentCount": {"$size": "$comments"}
              }
            }
          ],
          "as": "commentCount"
        }
      },
      {
        "$project": {
          "_id": 0,
          "postID": 1,
          "title": 1,
          "commentCount": {"$first": "$commentCount.commentCount"}
        }
      }
    ])
    

    Try it on mongoplayground.net.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search