Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following document structure:

"messages": {
"_id" : ObjectId("515a4de9c1a3c09c19000001"),
"author" : "50fd0d38c1a3c04c27000000",recipient" : "5159a292c1a3c01d5b000005",
"conversation" : [
    {
        "author" : "50fd0d38c1a3c04c27000000",
        "date" : ISODate("2013-04-02T03:18:01.204Z"),
        "message" : "hello test",
        "read" : false
    },
    {
        "message" : "reply test",
        "date" : ISODate("2013-04-02T03:36:57.444Z"),
        "author" : "5159a292c1a3c01d5b000005",
        "read" : true
    }....

Is it possible to get the total number of conversation messages where conversation.read is false and the author (conversation.author) of the unread message is not the person who started the conversation?

I'm currently finding documents that have conversations.read as false and then looping through them in PHP to check the conversations.author field. This works but I'm afraid when I get lots of data it will slow down.

I'm using the PHP MongoDB driver.

I have tried this..

$unread_conversations = $db->messages->find(
    array(
        'conversation.read'=>false
        'conversation.author'=>array('$ne'=>$_SESSION['account']['_id']->__toString())
    ));

but thats not working because I want the messages that are not read and not an author.

share|improve this question
What have you tried so far/what does your code look like? Have you read the query operators page? docs.mongodb.org/manual/reference/operators – Sverri M. Olsen Apr 2 at 4:33

1 Answer

This is not possible with regular mongo queries. You have to use map-reduce or mongos built in aggregation framework.

To accomplish your goal with current schema, you have to unwind nested list first.

Other solution is to change your schema and store each conversation as a separated document (with parent filed which contains the id of parent conversation).

And just as a side note: don't store id fields as string, always use ObjectId to store mongo ids.

share|improve this answer
I've updated my ids to use ObjectIds but haven't been able to work out the aggregation framework. This is what I've been trying:db.messages.aggregate({$project:{"conversation":1}},{$match:{"conversatio‌​n.author":ObjectId("5160d499c1a3c0cb2d000002")}},{"$unwind":"$conversation"}) – Castles Apr 16 at 1:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.