2017-08-20 5 views
0

というユーザーというコレクションがあり、埋め込みドキュメントメッセージが含まれています。SpringデータMongoDB集約に巻き戻し、一致、ソート&グループが含まれます

{ 
    "_id" : ObjectId("58e09daa192216e39fd85433"), 
    "userId" : "user123", 
    "message" : [ 
    { 
     "messageId" : "5277941e-9d84-46c3-b927-ef33abbf35f2", 
     "dateCreated" : 1491115000, 
     "body" : "howdy?", 
     "type" : "text" 
    }, 
    { 
     "messageId" : "c2ce0480-bc0d-4393-89d4-27174d323b98", 
     "dateCreated" : 1491119000, 
     "body" : "i've problem with my account. can you help?", 
     "type" : "text" 
    }, 
    { 
     "messageId" : "45b2593c-a960-4066-8723-db2531dd8bab", 
     "dateCreated" : 1491100000, 
     "body" : "this is urgent", 
     "type" : "text" 
    } 
    ] 
} 

私の目標は、埋め込まれた文書dateCreatedキーに基づいてメッセージを並べ替えることである:埋め込まれた文書メッセージは、以下のようにメッセージオブジェクトの配列が含まれています。私は春のデータのMongoDBにこのMongoのクエリを変換する必要があります。

db.user.aggregate(
    {$unwind: "$message"}, 
    {$match: {userId: "user123"}}, 
    {$sort: {"message.dateCreated": 1}}, 
    {$group: {_id: "$_id", "message": {"$push": "$message"}}}) 

私は以下のコードを試してみましたが、まだエラーを取得しました:

AggregationOperation unwind = Aggregation.unwind("message"); 
AggregationOperation match = Aggregation.match(Criteria.where("userId").in("user123")); 
AggregationOperation sort = Aggregation.sort(Direction.ASC, "message.dateCreated"); 
AggregationOperation group = Aggregation.group("userId", "message"); 

Aggregation aggregation = Aggregation.newAggregation(unwind, match, sort, group); 

AggregationResults<User> groupResults = mongoTemplate.aggregate(aggregation, User.class, User.class); 

エラー:

はインスタンス化に失敗しました[ java.util.List]:指定されたクラスはインタフェースです

Userクラス:

@Document(collection="user") 
public class User { 

    @Id 
    private String id; 
    private String userId; 
    @Field("message") 
    @DBRef 
    private List<Message> message; 
    //constructor, getter, setter 
} 

Messageクラス:

@Document 
public class Message { 
    private String messageId; 
    private long dateCreated; 
    private String body; 
    private String type; 
    //constructor, getter, setter 
} 

ヒント:

私の研究に基づいて、私はGroupOperationBuilderグループ= Aggregation.groupを(使用する必要があることを確信しています"userId")。push( "message")しかし、AggregationResultsは私がmongoTemplate.aggregate()にそれを使用することを許可しないので、これをどのように進めるか分かりません。

答えて

0

最適化クエリは次のようになります。あなたが最初にそれはあなたの条件に一致する文書をフィルタしますこの特定のクエリを使用している場合

db.user.aggregate(
{$match: {userId: "user123"}}, 
{$unwind: "$message"}, 
{$sort: {"message.dateCreated": 1}}, 
{$group: {_id: "$_id", "message": {"$push": "$message"}}}); 

は、それがフィルタリング文書をアンワインドします。

関連する問題