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.
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.
Share Improve this question asked Aug 24, 2012 at 10:08 user1596798user1596798 711 silver badge2 bronze badges2 Answers
Reset to default 9MongoDB has a distinct() mand 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 mon query type for your application, you should add appropriate indexes .. for example, on fromPerson
or (fromPerson, toPerson)
.
Take a look at the mongodb documentation at this page. It describes how to create a distinct query.