我正在开发一个使用Codeigniter和MongoDB的Web应用程序。 在数据库中我得到了一个文件,如下所示:在MongoDB文档中查找匹配的数组项目
{
"_id": {
"$id": "4f609932615a935c18r000000"
},
"basic": {
"name": "The project"
},
"members": [
{
"user_name": "john",
"role": "user",
"created_at": {
"sec": 1331730738,
"usec": 810000
}
},
{
"user_name": "markus",
"role": "user",
"created_at": {
"sec": 1331730738,
"usec": 810000
}
}
]
}
我需要同时使用user_name和作用,该文件搜索。现在,当我使用下面的代码时,我得到了两个。我只想获得匹配user_name和role的数组项目。
$where = array (
'_id' => new MongoId ($account_id),
'members.user_id' => new MongoId ($user_id),
'members.role' => $role
);
$this -> cimongo -> where ($where) -> count_all_results ('accounts');
好,为2.2,你可以使用相同的$ elemMatch标准作为投影过,那么你会在你的结果得到的只是匹配的元素。不过要注意的是:当在投影中使用时,elemMatch将仅返回FIRST匹配元素。没有办法不幸的返回多个比赛。请参阅:http://docs.mongodb.org/manual/reference/projection/elemMatch/ – UpTheCreek 2013-02-26 12:28:25