我正在使用mongodb做项目。所以在这里我只需要检索文档元素的数组搜索文档的选定字段。这是我的榜样。
{
"_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”:“它测试我”} 我是怎么做到的请帮帮我。
答案 0 :(得分:0)
我不确定是否有一种直接的方式来做你想做的事情,但你可以尝试以下方法:
如果文档中的事件不超过1 ,您只需进行投影:
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"
}
]
}
但是,您仍会以键值格式获得结果。如果您使用的是驱动程序,也许可以轻松检索该值。
如果文档中的事件可能超过1 ,我担心您只能使用$elemMatch
为每个匹配的文档获取第一个匹配的子文档:
db.events.find({"events.subject":"it test I"},{events:{$elemMatch:{"subject":"it test I"}},_id:0}).pretty()
你得到的结果与no相同。 1。
您可以尝试使用聚合框架来检索所有匹配的文档:
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
}