2012-08-24 28 views
6

因此,可以說我的chatsDB充滿了這樣的數據:如何僅抓取mongoDB和流星中的不同值?

{_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!"} 

我想從這個查詢的MongoDB返回一個唯一的結果集。我該怎麼做呢?

例如,在SQL + PHP:

Select fromPerson Distinct from chatsDB;

我的想法,現在是呈現從列表,並給人們的模板,以獲得人民的用戶講話的「chatUserList」用。

回答

-1

查看this page的mongodb文檔。它描述瞭如何創建一個獨特的查詢。

6

MongoDB有一個distinct()命令,它在這種情況下完全符合你的要求。

例發現不同的發件人的所有聊天記錄:在使用查詢過濾器

> db.chatsDB.distinct('fromPerson'); 
[ "John Smith", "Tom Smith", "Bob Smith" ] 

例如,要查找獨特的人將消息發送到「約翰·史密斯」:

> db.chatsDB.distinct('fromPerson', { toPerson: 'John Smith'}); 
[ "Bob Smith" ] 

如果這將是一個常見的查詢類型爲您的應用程序,您應該添加適當的索引..例如,在fromPerson(fromPerson, toPerson)

+0

但我使用流星和流星的集合,以我的理解不允許你做db.chatsDB。任何東西... 例如我有: Messages = new Meteor.Collection('messages'); 然後我會調用Messages.find(); – user1596798

+1

我有同樣的問題試圖運行一個獨特的流星。 Javascript控制檯說 .distinct不是一個函數。所以我想它在Meteor中不被支持? – Poliquin

+4

原來流星還沒有爲MongoDB的'distinct()'或'aggregate()'特性提供幫助:(具有'distinct'函數原型的更相關的答案是:[StackOverflow:mongodb distinct()在服務器上](http://stackoverflow.com/questions/14901761)。這是基於[pull(請求)](https://github.com/meteor/meteor/pull/644)出現已關閉但未合併。 – Stennie