我有不同领域的电影数据库。 Genre 字段包含一个逗号分隔的字符串,例如:
{genre: 'Action, Adventure, Sci-Fi'}
我知道我可以使用正则表达式来查找匹配项。我也试过:
{'genre': {'$in': genre}}
问题是运行时间。返回查询结果需要很多时间。该数据库有大约 30 万个文档,我已经对“流派”字段进行了正常索引。
最佳答案
会说使用 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}})
输出:
/* 0 */
{
"_id" : ObjectId("55842af93cab061ff5c618ce"),
"value" : [
"Action",
"Adventure",
"Sci-Fi"
]
}
/* 1 */
{
"_id" : ObjectId("55842af93cab061ff5c618d0"),
"value" : [
"Comedy",
"Action"
]
}
关于regex - 如何在mongodb中搜索逗号分隔的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30940908/