Book tagging with mongodb (many-to-many) implement

2019-05-18 09:16发布

Im trying to build a simple application in python, where I have tags that I associated to tags.

Given the following data:

Book:

+-------------+--------------------------------+
|     id      |             tags               |
+-------------+--------------------------------+
|      1      |     [python, ruby, rails]      |
+-------------+--------------------------------+
|      2      |     [fiction, fantasy]         |
+-------------+--------------------------------+
|      3      |     [fiction, adventure]       |
+-------------+--------------------------------+

How would I (using pymongo) find:

  1. All books tagged as "fiction"
  2. All unique tags in the system

1条回答
聊天终结者
2楼-- · 2019-05-18 09:27

1. Find all books by tag:

db.books.find({tags: 'ruby'})

This will be faster if you index the field.

db.books.ensureIndex({tags: 1})

2. Find all unique tags

You can use map-reduce

var map = function() {
  this.tags.forEach(function(t) {
    emit(t, 1);
  })
};

var reduce = function(k, vals) {
  return {k, 1}
};

db.books.mapReduce(map, reduce, {out: 'temp_collection_name'});

All examples are in javascript, they should work right away in mongo shell. I leave it to you to read the pymongo docs and translate the snippets.

查看更多
登录 后发表回答