繁体   English   中英

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

[英]How to search comma separated data in mongodb

我有不同领域的电影数据库。 Genre字段包含逗号分隔的字符串,如:

{genre: 'Action, Adventure, Sci-Fi'}

我知道我可以使用正则表达式来查找匹配项。 我也尝试过:

{'genre': {'$in': genre}}

问题是运行时间。 返回查询结果需要花费大量时间。 数据库有大约300K文档,我已经对'genre'字段进行了正常的索引。

可以说使用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"
    ]
}

好吧,你不能真正有效地做到这一点,所以我很高兴你在你的问题上使用了“性能”标签。

如果要使用字符串中的“逗号分隔”数据执行此操作,则需要执行以下操作:

一般的正则表达式,如果它适合:

db.collection.find({ "genre": { "$regex": "Sci-Fi" } })

但效率不高。

或者通过$where评估JavaScript:

db.collection.find(function() {
     return ( 
         this.genre.split(",")
             .map(function(el) { 
                 return el.replace(/^\s+/,"") 
             })
             .indexOf("Sci-Fi") != -1;
    )
})

效率不高,可能与上述相同。

或者更好的是可以使用索引的东西,与数组分开并使用基本查询:

{
    "genre": [ "Action", "Adventure", "Sci-Fi" ] 
}

带索引:

db.collection.ensureIndex({ "genre": 1 })

然后查询:

db.collection.find({ "genre": "Sci-Fi" })

这就是你这么做的时候就这么简单。 真的很有效率。

你做出了选择。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM