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
}
CodePudding user response:
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)
CodePudding user response:
A pure js solution would be :
const posts = [
{
postID: '123',
comments: [
{
commentID: 'comment123',
comment: 'my Comment'
},
{
commentID: 'comment456',
comment: 'my Comment'
}
]
},
{
postID: '456',
comments: [
{
commentID: 'comment123',
comment: 'my Comment'
},
{
commentID: 'comment456',
comment: 'my Comment'
},
{
commentID: 'comment789',
comment: 'my Comment'
}
]
},
]
posts.forEach(post=>{
post.commentCount = post.comments.length
})
console.log(posts)
You can do that before returning from backend or after fetching in frontend,there is absolutely a more complicated solution you can use with mongo's db.collection.aggregate()
,later i can look it up if you like
Thing is that you dont even need it,at some point you are going to use this array for showing the messages,its going to be something like this :
posts.forEach((post,index)=>{
//do something with the current post
//index is the value you're looking for
})