S
S
Stopy2015-04-26 20:10:55
MongoDB
Stopy, 2015-04-26 20:10:55

How to do several searches in the database at the same time (nodejs, mongodb)?

There is a collection that stores comments, one of the comment fields is the id of the post to which it refers. How to make several finds so that you can display the number of comments for each post at a time (there will be several posts on the page at once)? And it is also unknown how many posts will be on the page. In general, everything should be like this: the script receives an array of post ids, makes queries to the database and returns an object of similar content:

{
  "10": 13,
  "11": 5,
  "12": 27
}

Or can it be done in a more concise way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Shikanov, 2015-04-26
@Stopy

You need to use $group :

> db.comments.insert({id_post: 1})
> db.comments.insert({id_post: 1})
> db.comments.insert({id_post: 1})
> db.comments.insert({id_post: 2})
> db.comments.insert({id_post: 2})
> db.comments.insert({id_post: 3})
> db.comments.aggregate([{$group: {_id: "$id_post", count: {$sum: 1}}}])
{ "_id" : 3, "count" : 1 }
{ "_id" : 2, "count" : 2 }
{ "_id" : 1, "count" : 3 }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question