tekknolagi
tekknolagi

Reputation: 11012

many to many relationship in mongodb

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 tags and torrents.

How would I format a query that gets all the torrent_ids 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

Answers (1)

M. Mennan Kara
M. Mennan Kara

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

Related Questions