【问题标题】:How to grab only distinct values in mongoDB and meteor?如何仅在 mongoDB 和流星中获取不同的值?
【发布时间】:2012-08-19 21:28:55
【问题描述】:

假设我的聊天数据库充满了这些数据:

{_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”。

【问题讨论】:

    标签: javascript mongodb chat meteor


    【解决方案1】:

    MongoDB 有一个 distinct() 命令,在这种情况下,它完全符合您的要求。

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

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

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

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

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

    【讨论】:

    • 但我正在使用流星和流星的集合,据我了解,不允许您执行 db.chatsDB。任何东西......例如我有: Messages = new Meteor.Collection('messages');然后我会调用 Messages.find();
    • 我在 Meteor 上运行 distinct 时遇到了同样的问题。 Javascript 控制台说 .distinct 不是函数。所以我猜 Meteor 不支持它?
    • 事实证明 Meteor 还没有 MongoDB 的 distinct()aggregate() 功能的助手:(。distinct 函数原型的更相关答案是:StackOverflow: mongodb distinct() implementation in Meteor on the server。这是基于关闭似乎已关闭但未合并的pull request for aggregate()
    • 解决方案没有提到 Meteor。
    【解决方案2】:

    查看this page 的 mongodb 文档。它描述了如何创建不同的查询。

    【讨论】:

      猜你喜欢
      • 2017-07-24
      • 2015-04-25
      • 2016-03-19
      • 2020-05-30
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      相关资源
      最近更新 更多