T
T
Tshmt2019-11-22 23:40:03
MongoDB
Tshmt, 2019-11-22 23:40:03

How to select unique mongo conversations?

Hello.
There is a collection of messages:
it contains many documents of the type:

_id:5d91fb7da4ed665ef5d691a3
body:"hello from me"
author:5d91facba4ed665ef5d6919c
target:5d91facba4ed665ef5d6222e
created_at:2019-09-30T12:56:29.342+00:00
__v:0

_id:5d91fb7da4ed665ef5d691a4
body:"hello from some user"
author:5d91facba4ed665ef5d6222e
target:5d91facba4ed665ef5d6919c
created_at:2019-09-30T12:56:29.342+00:00
__v:0

I am a logged in user and my id = 5d91facba4ed665ef5d6919c. I need to select messages that are related to me.
i make a match
{
  $or: [
    { target: ObjectId('5d91facba4ed665ef5d6919c') },
    { author: ObjectId('5d91facba4ed665ef5d6919c') }]
}

and I receive all the messages that I wrote to someone or someone wrote to me.
Question: How can I continue to build a pipeline in order to select unique interlocutors that do not repeat with the last message from me or from the interlocutor?
I am doing something like this:
oL8R8U2.png
uniqUsers = [ ...new Set(messages.map(el => el.author === '5d91facba4ed665ef5d6919c' ? el.target : el.author )) ]

received, let's say, unique id of those who corresponded with me.
I don't know how better...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
grinat, 2019-11-22
@grinat

No need to collect unique ids in an array, read about aggregation. Further it is necessary simply $group on fields from whom/to whom. If you need the last correspondence, then make a collection a dialog, for example, and when adding messages, add the last message there to lastMessage and then you will only pull the collection. No matter how Monga is about normal forms, redundant and duplicate data is the norm. If you need schemas, normal shapes and scaling, then take a graph database, like neo4j

T
Tshmt, 2019-11-23
@Tshmt

I thought of what you need, only 1 group

{
  _id: { $cond: [ {$eq:["$author",ObjectId('5d91facba4ed665ef5d6919c')]}, "$target", "$author" ] },
  lastMessage: { $last: "$body" },
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question