7

私の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!"}

この mongoDB にクエリを実行して、一意の結果セットを返したいと考えています。どうすればいいですか?

たとえば、SQL+php では次のようになります。

Select fromPerson Distinct from chatsDB;

私の今の考えは、ユーザーが話したことのある人の「chatUserList」を取得するために、from と to のリストを含むテンプレートをレンダリングすることです。

4

2 に答える 2

9

MongoDB has a distinct() command which does exactly what you're after in this case.

Example finding distinct senders for all chats:

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

Example using a query filter to find unique people sending messages to 'John Smith':

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

If this is going to be a common query type for your application, you should add appropriate indexes .. for example, on fromPerson or (fromPerson, toPerson).

于 2012-08-24T10:25:13.933 に答える
-1

このページでmongodbのドキュメントを見てください。個別のクエリを作成する方法について説明します。

于 2012-08-24T10:11:13.873 に答える