How to grab only distinct values in mongoDB and meteor?

chat, javascript, meteor, mongodb

Solution

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

Problem

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.

Original source