Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grab only distinct values in mongoDB and meteor?

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.

like image 593
user1596798 Avatar asked Aug 24 '12 10:08

user1596798


1 Answers

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).

like image 168
Stennie Avatar answered Oct 14 '22 00:10

Stennie