问题
I was wondering what is the best practice to get a count of related documents of a particular document in MongoDB.
Scenario is as follows: I need to get posts that users shared and I need to get total number of comments related to those posts as well.
I would like to use the MongoDB Aggregation way if possible (if that is the best way of doing it) I am aware how to perform this query using separate methods .count() and .find().
document in posts collection:
{
_id: ObjectId('5a66321e7e2043078bc3b88a'),
uid: 'UniqueIDofTheUser',
text: 'Post text'
}
document in comments collection
{
_id: ObjectId('5a66321e7e2043078bc3b88c'),
uid: 'UniqueIDofTheUser',
post_id: ObjectId('5a66321e7e2043078bc3b88a'),
text: 'Comment text'
}
Desired Result:
[
{
_id: ObjectId('5a66321e7e2043078bc3b88a'),
uid: 'UniqueIDofTheUser',
text: 'Post text',
commentsCount: 20
},
{
_id: ObjectId('5a66321e7e2043078bc3b88c'),
uid: 'UniqueIDofTheUser',
text: 'Another post',
commentsCount: 3
},
{
_id: ObjectId('5a6632e17e2043078bc3b88f'),
uid: 'UniqueIDofTheUser',
text: 'Some random post',
commentsCount: 4
},
]
回答1:
You can just do a $lookup
to pull the posted comments for each post with $size
on the returned comments for a count.
db.posts.aggregate(
[{ $lookup: {
from: "comments",
localField: "_id",
foreignField: "post_id",
as: "commentsCount"
} },
{ $addFields: { "commentsCount": { $size: "$commentsCount" } } }]
)
来源:https://stackoverflow.com/questions/48389112/mongodb-best-practice-to-count-related-documents