如何从给定字段小写的MongoDB返回文档?

时间:2014-03-12 03:03:47

标签: php mongodb mongodb-query aggregation-framework data-conversion

我正在使用PHP的Mongo扩展。

我在MongoDB中有一个两级文档的集合,每个文档都有一个"电子邮件"字段在第二级(即," user_data.email"字段)。我想要一个MongoCursor加载文档,每个文档都有小写。这可能吗?

数据集是~100000个文档,我已经对我的应用程序进行了分析,并且知道strtolower()对PHP端的结果是一个瓶颈。

1 个答案:

答案 0 :(得分:1)

有点痛苦。也许mapReduce

db.collection.mapReduce(
    function() {
        emit( this._id, values: {
            email: this.user_data.email.toLowerCase(),
            other: this.other_field.toLowerCase()
        });
    },
    function(){},
    {
        "out": { "replace": "newCollection" }
    }
)

然后使用.find()从新集合中获取结果。

或者您可以等待2.6,其中aggregate 返回光标

db.collection.aggregate([
    { "$project": { "email": { "$toLower": "$user_data.email" } } }
])

真的不确定你的用例。电子邮件被视为不区分大小写,因此任何匹配都应考虑到这一点。

但如果比较你的话,为什么不使用strcasecomp

在一天结束时,这可能是您更新数据的内容,然后确保始终使用电子邮件地址插入记录小写。