So lets say my chatsDB is filled with this data:
{_id: "39e92f36-5d0f-44b7-8948-89be9b85bd08", fromPerson: "John Smith", toPerson: "Bob Smith", message: "Hey Buddy"}
{_id: "39e92f36-5d0f-44b7-8948-89be9b85bd08", fromPerson: "John Smith", toPerson: "Joe Smith", message: "Hi how you doing"}
{_id: "39e92f36-5d0f-44b7-8948-89be9b85bd08", fromPerson: "Tom Smith", toPerson: "Bob Smith", message: "Hello Again!"}
{_id: "39e92f36-5d0f-44b7-8948-89be9b85bd08", fromPerson: "Bob Smith", toPerson: "John Smith", message: "Hello Again!"}
I want to return a unique set of results from querying this mongoDB. How do I do this?
For example in SQL+php:
Select fromPerson Distinct from chatsDB;
My thought right now is to render the template with a list of from and to people to get a "chatUserList" of the people a user has spoken with.
MongoDB has a distinct() command which does exactly what you're after in this case.
Example finding distinct senders for all chats:
> db.chatsDB.distinct('fromPerson');
[ "John Smith", "Tom Smith", "Bob Smith" ]
Example using a query filter to find unique people sending messages to 'John Smith':
> db.chatsDB.distinct('fromPerson', { toPerson: 'John Smith'});
[ "Bob Smith" ]
If this is going to be a common query type for your application, you should add appropriate indexes .. for example, on fromPerson
or (fromPerson, toPerson)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With