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

故事扮演 提交于 2019-12-08 03:47:21

问题


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:


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.



来源:https://stackoverflow.com/questions/11585655/book-tagging-with-mongodb-many-to-many-implementation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!