Reputation: 11012
I'm writing a small torrent indexer in Ruby (here) and would love to support MongoDB as an option for the database. Currently, I have the database set up with a many-to-many relationship between tag
s and torrent
s.
How would I format a query that gets all the torrent_id
s from a map table that match to all the tags in a given list?
I did this in SQL like this:
select torrent_id, count(*) num from tagmap where tag_id in (tag1, tag2, tag3, tag4) group by torrent_id having num = 4"
EDIT: I am right now working only with the collection with torrent_id
and tag_id
. That's all it has in there. So I'm mapping ids to ids and naught more.
Upvotes: 0
Views: 171
Reputation: 10222
It's better to create a collection to create the mapping consisting tag_id's and torrent_id's. Whenever you add a torrent, also add the torrents tags to the torrenttags collection. Index should be on tag_id.
You can use the following query syntax to get a list of torrents matching more than one tag.
db.tagmap.find({tag_id:{$in: ['tag1','tag2','tag3','tag4']}});
For Aggregation (group by, count) you need to use MapReduce
Upvotes: 1