建议使用Map-Reduce创建一个单独的集合,将genre
作为数组存储,其中的值来自逗号分隔的字符串。此后,您可以运行Map-Reduce作业并管理输出集合上的查询。
例如,我已经在foo
集合中创建了一些样本文档:
db.foo.insert([
{genre: 'Action, Adventure, Sci-Fi'},
{genre: 'Thriller, Romantic'},
{genre: 'Comedy, Action'}
])
下面的map/reduce操作将生成一个集合,您可以在其中应用高效的查询:
map = function() {
var array = this.genre.split(/\s*,\s*/);
emit(this._id, array);
}
reduce = function(key, values) {
return values;
}
result = db.runCommand({
"mapreduce" : "foo",
"map" : map,
"reduce" : reduce,
"out" : "foo_result"
});
查询将是直接的,利用在value
字段上具有多键索引的查询:
db.foo_result.createIndex({"value": 1});
var genre = ['Action', 'Adventure'];
db.foo_result.find({'value': {'$in': genre}})
输出:
{
"_id" : ObjectId("55842af93cab061ff5c618ce"),
"value" : [
"Action",
"Adventure",
"Sci-Fi"
]
}
{
"_id" : ObjectId("55842af93cab061ff5c618d0"),
"value" : [
"Comedy",
"Action"
]
}