所以可以说我的聊天数据库充满了这些数据:
{_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为例:
从chatsDB中选择Person Distinct;
我现在的想法是使用来自和去往人员的列表呈现模板,以获取用户与之交谈过的人的“chatUserList”。
最佳答案
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)
上。
关于javascript - 如何仅在 mongoDB 和 meteor 中获取不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12107319/