如何在MongoDB PHP中通过嵌入项查找文档

时间:2012-08-15 20:54:41

标签: php arrays mongodb

我有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"
}

想象一下,我有超过这个用户可以注册的文档。我想找到用户注册的所有比赛。到目前为止我有这样的事情:

$id = "50247314f501384b011019bc";
$user = array('userid1' => $id, 'userid2' => $id, 'userid3' => $id );
$team = array('teams' => $user);            
$result =$this->collection->find($team);
return $result;

有人可以帮我吗?

谢谢。

------ ------解决

$team = array('$or' => array(array('teams.userid1' => $id),
               array('teams.userid2' => $id), 
               array('teams.userid3' => $id)
                 ));            

$result =$this->collection->find($team);

1 个答案:

答案 0 :(得分:3)

您的数据结构很难查询,因为您有一系列嵌入式文档。只需稍微更改数据,您就可以更轻松地使用它。

我已将用户ID放入数组:

{
 "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()
db.contest.find(
        {'teams.members':'50247314f501384b011019bc'},
        {'contestname':1, 'description':1}
    )

这将返回此用户输入的匹配竞赛:

{
    "_id" : ObjectId("502c108dcbfbffa8b2ead5d2"),
    "contestname" : "Contest1",
    "description" : "java programming contest"
}
{
    "_id" : ObjectId("502c10a1cbfbffa8b2ead5d4"),
    "contestname" : "Contest3",
    "description" : "Grovy programming contest"
}