1

I am developing a web app using Codeigniter and MongoDB. In the database I got a document that look like this:

{
    "_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
            }
        }
    ]
}

I need to search this document using both user_name and role. Right now when I am using the below code I get both. I only want to get array items matching both user_name and 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');
Jonathan Clark
  • 19,726
  • 29
  • 111
  • 175

2 Answers2

4

This is an old question, but as of MongoDB 2.2 or so you can use the $ positional operator in a projection so that only the matched array element is included in the result.

So you can do something like this:

$this->cimongo->where($where)->select(array('members.$'))->get('accounts');
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
2

This is a repeat of this question:

Get particular element from mongoDB array

Also you might want to use $elemMatch

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray

Here is the rub -- you aren't going to be able to get the array items that match because mongo is going to return the entire document if those elements match. You will have to parse out the code client side. Mongo doesn't have a way to answer, "return only the array that matches."

Community
  • 1
  • 1
Spencer
  • 709
  • 5
  • 12
  • 2
    Well, as of 2.2 you can use the same $elemMatch criteria as a projection too, then you will get just the matching element in your results. Big caveat though: when used in a projection elemMatch will only return the FIRST matching element. No way to return multiple matches unfortunately. see: http://docs.mongodb.org/manual/reference/projection/elemMatch/ – UpTheCreek Feb 26 '13 at 12:28