7

所以可以说我的聊天数据库充满了这些数据:

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

4

2 回答 2

9

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

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

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

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

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

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

于 2012-08-24T10:25:13.933 回答
-1

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

于 2012-08-24T10:11:13.873 回答