2

I'm implementing a very simple conversation system on mongodb.

The idea should be that when I'm opening a convo, it should display send and received messages. It's OK so far and should be pretty easy, by using a simple query like this pseudocode:

(from "my_id" AND to "friend_id") OR (from "friend_id" AND to "my_id")

this should be pretty straightforward and simple, but querying just looks so complicated to me with mongodb (I'm coming from mysql).

I'm trying this, but it's not working at all, and can't find out where the error is.

$cursor =$collection->find
            (
                array('$or' =>
                    array('$and' => array("from"=>"$profile", "to"=>"$loggeduser")),
                    array('$and' => array("to"=>"$profile", "from"=>"$loggeduser"))
                )
            )->limit(50)->sort(array('date' => -1));

this returns nothing.... Where's the mistake?

Thanks in advance.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367

1 Answers1

1

Take a look at this page on how to do advanced MongoDB queries: http://www.mongodb.org/display/DOCS/Advanced+Queries

You can use a combination of the $and and $in operators to get what you need. Using the mongo shell, your query would look something like this:

db.yourCollectionName.find({$and: {from: {$in: ["toUser", "loggedOnUser"]}}, {to: {$in: ["toUser", "loggedOnUser"]}}})

I believe this may also give you the equivalent:

db.yourCollectionName.find({$and: {$or: [{from: "toUser"}, {to: "toUser"}]}}, {$or: [{from: "loggedOnUser"}, {to: "loggedOnUser"}]}}})

From there it's a matter of converting the above to the language/DSL that you're using, and sorting by date.

In your code, you don't need the ($and => array()) wrapping each of the objects that you're trying to find. Remove them, so it looks like this:

$cursor = $collection->find(
    array('$or' => 
        array(
            array("from"=>"$profile", "to"=>"$loggeduser"),
            array("to"=>"$profile", "from"=>"$loggeduser")
        )
    )
) ->limit(50)->sort(array('date' => -1));
Mike Cialowicz
  • 9,892
  • 9
  • 47
  • 76
  • yea I know that, that's what my code is, I'm sort of translating that to the PHP mongo driver code, but there must be some sort of mistake somewhere which I can't see.... perhaps someone will notice it... Thanks for the answer tho! –  Mar 08 '12 at 17:39
  • Take a look again at what I wrote. Remove the extra $and from each nested array. You don't need the ($and => array()) wrapping each object... you just need the $or, I believe. – Mike Cialowicz Mar 08 '12 at 17:44