如何只获取mongoDB和meteor中的不同值?

use*_*798 6 javascript chat mongodb meteor

那么就说我的chatsDB充满了这些数据:

{_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!"}
Run Code Online (Sandbox Code Playgroud)

我想通过查询这个mongoDB返回一组独特的结果.我该怎么做呢?

例如在SQL + php中:

Select fromPerson Distinct from chatsDB;

我现在的想法是渲染模板,其中包含来自和来自人的列表,以获得用户与之交谈过的人的"chatUserList".

Ste*_*nie 6

MongoDB有一个distinct()命令,它完全符合你在这种情况下所做的事情.

查找所有聊天的不同发件人的示例:

> db.chatsDB.distinct('fromPerson');
[ "John Smith", "Tom Smith", "Bob Smith" ]
Run Code Online (Sandbox Code Playgroud)

使用查询过滤器查找向"John Smith"发送消息的唯一人的示例:

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

如果这将是您的应用程序的常见查询类型,则应添加适当的索引...例如,on fromPerson(fromPerson, toPerson).

  • 事实证明,Meteor还没有MongoDB的`distinct()`或`aggregate()`特性的帮助:(.使用`distinct`函数原型的更相关的答案是:[StackOverflow:mongodb distinct()在Meteor上实现服务器](http://stackoverflow.com/questions/14901761).这是基于[pull()的拉取请求(https://github.com/meteor/meteor/pull/644)已经关闭但没有合并. (4认同)

Lyu*_*lev -1

查看此页面上的 mongodb 文档。它描述了如何创建不同的查询。