0

我在 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);
4

1 回答 1

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"
}
于 2012-08-15T21:22:09.327 回答