如何通过MongoDB PHP中的嵌入式项目查找文档 [英] How to find a document by embedded item in MongoDB PHP
问题描述
我在MongoDB中拥有下一个文档:
I have the next document in MongoDB:
比赛文件:
{
"_id": ObjectId("502aa915f50138d76d11112f7"),
"contestname": "Contest1",
"description": "java programming contest",
"numteams": NumberInt(2),
"teams": [
{
"teamname": "superstars",
"userid1": "50247314f501384b011019bc",
"userid2": "50293cf9f50138446411001c",
"userid3": "50293cdff501384464110018"
},
{
"teamname": "faculty",
"userid1": "50247314f501384b0110100c",
"userid2": "50293cf9f50138446410001b",
"userid3": "50293cdff501384464000019"
}
],
"term": "Fall 2012"
}
想象一下,除了我可以在这里注册用户之外,还有更多的文档.我想查找用户已注册的所有比赛.到目前为止,我有这样的事情:
Imagine that I have more than this document where users can register. I want to find all the contest that a user has registered. I have something like this so far:
$id = "50247314f501384b011019bc";
$user = array('userid1' => $id, 'userid2' => $id, 'userid3' => $id );
$team = array('teams' => $user);
$result =$this->collection->find($team);
return $result;
有人可以帮我吗?
谢谢.
------解决--------
------Solved------
$team = array('$or' => array(array('teams.userid1' => $id),
array('teams.userid2' => $id),
array('teams.userid3' => $id)
));
$result =$this->collection->find($team);
推荐答案
您的数据结构难以查询,因为您有一系列嵌入式文档.只需稍微更改一下数据,您就可以更轻松地使用它.
Your data structure is awkward to query because you have an array of embedded documents. With a slight change to the data you could make this easier to work with.
我已经将用户ID放入了一个数组:
I've put the user IDs into an array:
{
"contestname": "Contest1",
"description": "java programming contest",
"numteams": 2,
"teams": [
{
"teamname": "superstars",
"members": [
"50247314f501384b011019bc",
"50293cf9f50138446411001c",
"50293cdff501384464110018"
]
},
{
"teamname": "faculty",
"members": [
"50247314f501384b0110100c",
"50293cf9f50138446410001b",
"50293cdff501384464000019"
]
}
],
"term": "Fall 2012"
}
然后,您可以执行与PHP等价的 find():
You could then do the PHP equivalent find() for:
db.contest.find(
{'teams.members':'50247314f501384b011019bc'},
{'contestname':1, 'description':1}
)
这将返回该用户输入的匹配竞赛:
Which would return the matching contests this user had entered:
{
"_id" : ObjectId("502c108dcbfbffa8b2ead5d2"),
"contestname" : "Contest1",
"description" : "java programming contest"
}
{
"_id" : ObjectId("502c10a1cbfbffa8b2ead5d4"),
"contestname" : "Contest3",
"description" : "Grovy programming contest"
}
这篇关于如何通过MongoDB PHP中的嵌入式项目查找文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!