regex - 如何在mongodb中搜索逗号分隔的数据

标签 regex performance mongodb mongodb-query

我有不同领域的电影数据库。 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/

相关文章:

MongoDB Stitch 返回数据作为 $NumberDouble 而不是数字本身

正则表达式捕获只有 2 位数字的字符串

regex - Perl正则表达式定界符/.../和#...#之间的区别

javascript - 替换ckeditor中的内容标签html

MongoDB,选择嵌套数组字段

ruby-on-rails - Rails Geocoder near 方法将结果限制为 100

Python:If 语句 "If not none"处理

android - 在整个 Activity 中重复使用 String 或 Int?

android - 如何使用 fragment 创建后才可用的数据填充 fragment ?

algorithm - 在二叉搜索树中插入一个新值