chris1069603
chris1069603

Reputation: 443

Query unread messages

I'm stuck with some MongoDB query. I have a simple structure to manage threads and messages in my application.

{
  participants: [
    'u1,'u2'
  ]
  messages: [
   {text: 'some message', readBy: ['u1','u2']}
   {text: 'some other message', readBy: ['u1']}
  ]
}

Being 'u2' I would like to get this specific thread returned by the query. This is how far I have come, but as soon as one message was read by 'u2', it is not returned anymore as one of the messages has been read by 'u2'.

Threads.find(
        {
            $and: [
                {'participants': this.userId},
                {'messages.readBy': {$nin: [this.userId]}}        
            ]
        }            
    )

How can I achieve this without changing my datastructure?

Upvotes: 1

Views: 470

Answers (1)

Bertrand Martel
Bertrand Martel

Reputation: 45372

You can use an aggregation to perform an $unwind operation that will transform your messages array in Json object which will help you to request exactly the item you need.

The following query will give you the records where "u2" is participating with only messages not read by "u2" :

db.threads.aggregate([{
    $unwind: "$messages"
}, {
    $match: {
        "participants": "u2",
        "messages.readBy": {
            $nin: ["u2"]
        }
    }
}]);

this will give you :

{
    "_id": ObjectId("579d0fc8733ac30906524be4"),
    "participants": ["u1", "u2"],
    "messages": {
        "text": "some other message",
        "readBy": ["u1"]
    }
}

Upvotes: 1

Related Questions