简体   繁体   中英

PHP + MongoDB - Fetch entry from array inside collection with $elemMatch not working

I have the following object:

{
    users: {
        _id: "users",
        entries: 
        [
            {
                _id: 1,
                username: "taxicala",
                password: "password"
            },
            {
                _id: 2,
                username: "guest",
                password: "guest"
            }
        ]
    }
}

And I want to select only one user that is within the "entries" array. I am trying the following:

$entry = $this->_users->find(
             array('entries' => 
                 array('$elemMatch' => 
                     array('username' => 'taxicala')
                 )
             )
         );

The result I get is an empty object:

{ }

I could not find any clue over Google or here about this. Am I doing something wrong? Am I missing something? or is '$elemMatch' not supported by PHP?

Thanks!

$elemMatch is supported but as far as you document goes, you entries are inside the user object . So at least in your query you have to put array('users.entries' => ...) . Also I do not see why do you need to use $elemMatch.

db.coll.find({"users.entries.username" : "taxacala"}) outputs the documents with username "taxacala".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM