Php 使用mongodb如何在文档字段数组上检索部分文档搜索
我正在使用mongodb做项目。所以在这里,我只需要在文档元素数组上检索文档搜索的选定字段。这是我的例子Php 使用mongodb如何在文档字段数组上检索部分文档搜索,php,mongodb,Php,Mongodb,我正在使用mongodb做项目。所以在这里,我只需要在文档元素数组上检索文档搜索的选定字段。这是我的例子 { "_id": { "$id": "515ce66ca00b2aa30a000000" }, "user_id": "user_1111", "events": [ { "subject": "it test I",
{
"_id": {
"$id": "515ce66ca00b2aa30a000000"
},
"user_id": "user_1111",
"events": [
{
"subject": "it test I",
"start_date": "04/14/2013",
"start_time": "8.00 AM",
"end_date": "04/14/2013",
"end_time": "10.30 AM",
"all_day_event": "false",
"discription": "no discription",
"location": "STC",
"private": "false",
"time_zone": "IST",
"alarm": "true",
"alarm_threshold": "5",
"status": "true"
}
]
}
所以这里我需要检索以下结果
{
"subject": "it test I",
"start_date": "04/14/2013",
"start_time": "8.00 AM",
"end_date": "04/14/2013",
"end_time": "10.30 AM",
"all_day_event": "false",
"discription": "no discription",
"location": "STC",
"private": "false",
"time_zone": "IST",
"alarm": "true",
"alarm_threshold": "5",
"status": "true"
}
搜寻
{“events.subject”:“it test I”}
我是怎么做到的。请帮帮我
我不确定是否有一个简单的方法来做你想做的事情,但你可以尝试以下方法:
db.events.find({"events.subject":"it test I"},{events:1,_id:0}).pretty()
{
"events" : [
{
"subject" : "it test I",
"start_date" : "04/14/2013",
"start_time" : "8.00 AM",
"end_date" : "04/14/2013",
"end_time" : "10.30 AM",
"all_day_event" : "false",
"discription" : "no discription",
"location" : "STC",
"private" : "false",
"time_zone" : "IST",
"alarm" : "true",
"alarm_threshold" : "5",
"status" : "true"
}
]
}
但是,您仍将以键值格式获得结果。如果您使用的是驱动程序,也许可以轻松检索该值$elemMatch
为每个匹配文档获取第一个匹配的子文档:
db.events.find({"events.subject":"it test I"},{events:{$elemMatch:{"subject":"it test I"}},_id:0}).pretty()
你得到的结果和第一名一样db.events.aggregate(
{$match: {"events.subject":"it test I"}},
{$unwind: "$events"},
{$match: {"events.subject":"it test I"}},
{
$project:{
_id: 0,
subject: "$events.subject",
start_date: "$events.start_date",
end_date: "$events.end_date",
end_time: "$events.end_time",
all_day_event: "$events.all_day_event",
discription: "$events.discription",
location: "$events.location",
private: "$events.private",
time_zone: "$events.time_zone",
alarm: "$events.alarm",
alarm_threshold: "$events.alarm_threshold",
status: "$events.status"
}
})
{
"result" : [
{
"subject" : "it test I",
"start_date" : "04/14/2013",
"end_date" : "04/14/2013",
"end_time" : "10.30 AM",
"all_day_event" : "false",
"discription" : "no discription",
"location" : "STC",
"private" : "false",
"time_zone" : "IST",
"alarm" : "true",
"alarm_threshold" : "5",
"status" : "true"
}
],
"ok" : 1
}