问题
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:
- All books tagged as "fiction"
- 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