2016-03-22 17 views
3

私は新しいMongodbです。私はJavaのスプリングで$ lookupに問題があります。

私はGoogleで見つかりましたが、応答なしまだ

db.NewFeed.aggregate([ 
    { 
     $match : {username : "user001"} 
    }, 
    { 
     $lookup: 
     { 
      from: "NewfeedContent", 
      localField: "content.contentId", 
      foreignField: "_id", 
      as: "NewfeedContent" 
     } 
    } 
]) 

春データにこのシェルを使用したいと思います。

+0

エラーはありますか?何がうまくいかないか説明できますか? – Sanj

答えて

4

すべての「新しい」機能によって、すぐになどの抽象化レイヤーに変換されるわけではありません。

ので、代わりに、あなたが必要とするすべてではなく、それはコンテンツだとして直接指定BSONオブジェクトを取るAggregationOperationインタフェースを、使用するクラスを定義している:

public class CustomAggregationOperation implements AggregationOperation { 
    private DBObject operation; 

    public CustomAggregationOperation (DBObject operation) { 
     this.operation = operation; 
    } 

    @Override 
    public DBObject toDBObject(AggregationOperationContext context) { 
     return context.getMappedObject(operation); 
    } 
} 

その後、あなたはこのようなあなたの集計に使用することができます:match()パイプラインヘルパーに建てられたと混合カスタムクラスを示し

Aggregation aggregation = newAggregation(
    match(
     Criteria.where("username").is("user001") 
    ), 
    new CustomAggregationOperation(
     new BasicDBObject(
      "$lookup", 
      new BasicDBObject("from", "NewFeedContent") 
       .append("localField","content.contentId") 
       .append("foreignField", "_id") 
       .append("as", "NewFeedContent") 
     ) 
    ) 
) 

各ヘルパーの下で発生するのは、とにかくDBObjectなどのBSON表現にシリアライズすることだけです。したがって、コンストラクタはオブジェクトを直接取得し、.toDBObject()から直接返します。これは、piplineの内容をシリアル化するときに呼び出されるインターフェイスの標準メソッドです。ここで

+0

ありがとうございました。D –

+0

SpringデータMongoでルックアップ操作がサポートされるようになりました。https://docs.spring.io/spring-data/mongodb/docs/1.10.x/api/org/springframework/data/mongodb/core/aggregation /Aggregation.html#lookup-java.lang.String-java.lang.String-java.lang.String-java.lang.String- – macias

2

は一例です:

コレクションの記事検索と一致

{ 
"_id" : ObjectId("5a198074ed31adaf5d79fe8a"), 
"title" : "Post 1", 
"authors" : [1, 2] 
}, 
{ 
"_id" : ObjectId("5a198074ed31adaf5d79fe8d"), 
"title" : "Post 2", 
"authors" : [2] 
} 

コレクションユーザー

{ 
"_id" : ObjectId("5a18b483ed31ada08fd6ed82"), 
"userId" : 1, 
"name" : "Vinod Kumar" 
}, 
{ 
"_id" : ObjectId("5a18b483ed31ada08fd6ed83"), 
"userId" : 2, 
"name" : "Jim Hazel" 
}, 
{ 
"_id" : ObjectId("5a18b483ed31ada08fd6ed84"), 
"userId" : 3, 
"name" : "Alex Wong" 
} 

MongoDBのクエリ

春Mongoopration構文

LookupOperation lookupOperation = LookupOperation.newLookup(). 
      from("posts"). 
      localField("userid"). 
      foreignField("authors"). 
      as("post"); 

AggregationOperation match = Aggregation.match(Criteria.where("post").size(1)); 


Aggregation aggregation = Aggregation.newAggregation(lookupOperation, match); 

List<BasicDBObject> results = mongoOperation.aggregate(aggregation, "users", BasicDBObject.class).getMappedResults(); 
関連する問題