使用 mongodb(多对多)实现进行书籍标记 [英] Book tagging with mongodb (many-to-many) implementation

查看:66
本文介绍了使用 mongodb(多对多)实现进行书籍标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 python 构建一个简单的应用程序,其中我有与标签关联的标签.

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

给定以下数据:

预订:

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

我将如何(使用 pymongo)找到:

How would I (using pymongo) find:

  1. 所有标记为小说"的书籍
  2. 系统中的所有唯一标签

推荐答案

1.按标签查找所有图书:

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

如果您为该字段编制索引,这会更快.

This will be faster if you index the field.

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

2.查找所有唯一标签

你可以使用 map-reduce

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'});

所有示例都在 javascript 中,它们应该立即在 mongo shell 中工作.我让您阅读 pymongo 文档并翻译片段.

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.

这篇关于使用 mongodb(多对多)实现进行书籍标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆