Bobby
Bobby

Reputation: 4502

PHP MongoDB findone $and

How would I find a row with two objects? Example:

    $m = new Mongo();
    $db = $m->mydb->user_tokens;
    $cursor = $db->findOne(array('$and' => array('user_id' => $userid, 'token_id' => $tokenid)));

I'm not sure if you can even do this in PHP. I have a python backend server that I can do something similar to this but need to be able to do it on the frontend as well.

Upvotes: 0

Views: 2902

Answers (1)

Petrogad
Petrogad

Reputation: 4423

You don't need the $and qualifier; just setting your two conditions should work fine.

In php one thing I've found useful is to take your query; then do a:

echo(json_encode($query));   

This way you can take your query and try it directly on the console to confirm it's showing what you're thinking it should.

A bit further into the above explained.. Currently this is what you're querying on:

{"$and":{"user_id":"userId","token_id":"tokenId"}}

I found this out by doing

echo(json_encode(array('$and' => array('user_id' => 'userId', 'token_id' => 'tokenId'))));

You want to be doing either:

{"$and":[{"user_id":"userId"},{"token_id":"tokenId"}]}

or

{"user_id":"userId","token_id":"tokenId"}

Useful sheet to look up when creating your queries:

SQL to Mongo Cheat Sheet

Upvotes: 3

Related Questions