在MongoDB文档中查找匹配的数组项

23 浏览
0 Comments

在MongoDB文档中查找匹配的数组项

我正在使用Codeigniter和MongoDB开发一个Web应用程序。

在数据库中,我有一个文档,看起来像这样:

{

"_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和role两个条件来搜索这个文档。目前,当我使用下面的代码时,我会得到两者的匹配结果。但我只想获得匹配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');

0
0 Comments

问题的原因:在MongoDB文档中查找匹配的数组项。

解决方法:使用MongoDB 2.2或更高版本中的$位置操作符,在投影中只包含匹配的数组元素。

代码示例:

$this->cimongo->where($where)->select(array('members.$'))->get('accounts');

0
0 Comments

问题的出现原因:MongoDB无法直接返回匹配的数组元素,而是会返回整个文档。

解决方法:使用$elemMatch操作符进行查询,并在投影中使用相同的$elemMatch条件,这样可以只返回匹配的元素。但是需要注意的是,$elemMatch在投影中只会返回第一个匹配的元素,无法返回多个匹配的元素。

参考链接:

- [Get particular element from mongoDB array](https://stackoverflow.com/questions/5562485)

- [Advanced Queries - Value in an Array](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray)

- [Projection - elemMatch](http://docs.mongodb.org/manual/reference/projection/elemMatch/)

0