如何在多维数组中搜索值,
例如,我想在mongodb中的以下数据中搜索example
关键字
我曾经从命令
>db.info.find()
{
"_id" : ObjectId("4f74737cc3a51043d26f4b90"),
"id" : "12345",
"info" : [
{
"sno" : 1,
"name" : "ABC",
"email" : "abc@example.com"
},
{
"sno" : 2,
"name" : "XYZ",
"email" : "xyz@example.com"
},
{
"sno" : 3,
"name" : "XYZ",
"email" : "xyz@demo.com"
},
{
"sno" : 4,
"name" : "ABC",
"email" : "abc@demo.com"
},
{
"sno" : 5,
"name" : "Rohan",
"email" : "rohan@example.com"
}
]
}
现在,要查找具有example
的数据,我使用了命令
>db.info.find({"info.email":"example"})
它给出了
{
"_id" : ObjectId("4f74737cc3a51043d26f4b90"),
"id" : "12345",
"info" : [
{
"sno" : 1,
"name" : "ABC",
"email" : "abc@example.com"
},
{
"sno" : 2,
"name" : "XYZ",
"email" : "xyz@example.com"
},
{
"sno" : 3,
"name" : "XYZ",
"email" : "xyz@demo.com"
},
{
"sno" : 4,
"name" : "ABC",
"email" : "abc@demo.com"
},
{
"sno" : 5,
"name" : "Rohan",
"email" : "rohan@example.com"
}
]
}
但我只想要5个子行中的3个,比如
{
"_id" : ObjectId("4f74737cc3a51043d26f4b90"),
"id" : "12345",
"info" : [
{
"sno" : 1,
"name" : "ABC",
"email" : "abc@example.com"
},
{
"sno" : 2,
"name" : "XYZ",
"email" : "xyz@example.com"
},
{
"sno" : 5,
"name" : "Rohan",
"email" : "rohan@example.com"
}
]
}
答案 0 :(得分:2)
Rohan,MongoDB始终返回您正在搜索的整个文档。您不能只返回找到关键字的数组元素。如果您想这样做,那么您需要确保“info”字段中的所有嵌入文档都在他们自己的集合中。这可能意味着您需要将它们链接回“info”集合中的原始文档。也许是这样的事情:
{
"sno" : 1,
"name" : "ABC",
"email" : "abc@example.com"
"info_id" : "12345",
},
或者,您当然可以在PHP中进行后处理,以仅获取您想要的行。
答案 1 :(得分:1)
答案 2 :(得分:1)
我尝试了Map Reduce Function,它适用于这类问题代码就是这样:
写一个地图功能
map=function ()
{
filter = [];
this.info.forEach(function (s) {if (/example/.test(s.email)) {filter.push(s);}});
emit(this._id, {info:filter});
}
写一个reduce函数
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" : "abc@example.com"
},
{
"sno" : 2,
"name" : "XYZ",
"email" : "xyz@example.com"
},
{
"sno" : 5,
"name" : "Rohan",
"email" : "rohan@example.com"
}
]
}
}
],
"timeMillis" : 1,
"counts" : {
"input" : 3,
"emit" : 3,
"reduce" : 0,
"output" : 3
},
"ok" : 1,
现在您可以从
找到您的搜索数据 printjson(res.results)
答案 3 :(得分:0)