Jonathan Clark
Jonathan Clark

Reputation: 20538

Find matching array items in MongoDB document

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');

Upvotes: 1

Views: 20547

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311875

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');

Upvotes: 4

Spencer
Spencer

Reputation: 727

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."

Upvotes: 2

Related Questions