如何使用mongodb搜索内部数组中的字符串?
如何多维数组搜索值, 比如我想搜索在MongoDB中 以下数据example
关键字我用来从命令如何使用mongodb搜索内部数组中的字符串?
>db.info.find()
{
"_id" : ObjectId("4f74737cc3a51043d26f4b90"),
"id" : "12345",
"info" : [
{
"sno" : 1,
"name" : "ABC",
"email" : "[email protected]"
},
{
"sno" : 2,
"name" : "XYZ",
"email" : "[email protected]"
},
{
"sno" : 3,
"name" : "XYZ",
"email" : "[email protected]"
},
{
"sno" : 4,
"name" : "ABC",
"email" : "[email protected]"
},
{
"sno" : 5,
"name" : "Rohan",
"email" : "[email protected]"
}
]
}
获取所有数据现在,找到数据具有example
我用命令
>db.info.find({"info.email":"example"})
和它给
{
"_id" : ObjectId("4f74737cc3a51043d26f4b90"),
"id" : "12345",
"info" : [
{
"sno" : 1,
"name" : "ABC",
"email" : "[email protected]"
},
{
"sno" : 2,
"name" : "XYZ",
"email" : "[email protected]"
},
{
"sno" : 3,
"name" : "XYZ",
"email" : "[email protected]"
},
{
"sno" : 4,
"name" : "ABC",
"email" : "[email protected]"
},
{
"sno" : 5,
"name" : "Rohan",
"email" : "[email protected]"
}
]
}
但我想只有3个5个个子行像
{
"_id" : ObjectId("4f74737cc3a51043d26f4b90"),
"id" : "12345",
"info" : [
{
"sno" : 1,
"name" : "ABC",
"email" : "[email protected]"
},
{
"sno" : 2,
"name" : "XYZ",
"email" : "[email protected]"
},
{
"sno" : 5,
"name" : "Rohan",
"email" : "[email protected]"
}
]
}
我试过的Map Reduce函数,它适用于这类问题的代码是类似的东西:
写地图功能
map=function()
{
filter = [];
this.info.forEach(function (s) {if (/example/.test(s.email)) {filter.push(s);}});
emit(this._id, {info:filter});
}
写减少功能
reduce=function(key, values) { return values;}
MapReduce功能
res=db.info.mapReduce(map,reduce,{out:{inline:1}})
和输出看喜欢:
"results" : [
{
"_id" : ObjectId("4f9a2de0ea4a65c3ab85a9d3"),
"value" : {
"info" : [
{
"sno" : 1,
"name" : "ABC",
"email" : "[email protected]"
},
{
"sno" : 2,
"name" : "XYZ",
"email" : "[email protected]"
},
{
"sno" : 5,
"name" : "Rohan",
"email" : "[email protected]"
}
]
}
}
],
"timeMillis" : 1,
"counts" : {
"input" : 3,
"emit" : 3,
"reduce" : 0,
"output" : 3
},
"ok" : 1,
现在你可以从
printjson(res.results)
Rohan,MongoDB始终返回您正在搜索的整个文档。您不能仅仅让它返回发现关键字的数组元素。如果你想这样做,那么你需要确保“info”字段中的所有嵌入文档都在它们自己的集合中。这可能意味着您需要将它们链接回“info”集合中的原始文档。也许类似于:
{
"sno" : 1,
"name" : "ABC",
"email" : "[email protected]"
"info_id" : "12345",
},
或者,您当然也可以在PHP中进行后处理以仅获取所需的行。
Derick我们可以说这是mongodb的缺点吗? – 2012-04-12 10:43:50
这是MongoDB不是为此设计的。您需要意识到,尽管您的地图缩减解决方案将具有完全不同的性能特征,并且当您同时执行此操作时可能会变得更糟糕。我仍然会建议它在客户端做。 – Derick 2012-04-27 10:56:16
它会给整个文档未搜索到的内阵列的数据。 – 2012-04-28 06:51:33