Spring数据mongo中的MongoDB $ Lookup

裴先生:

我是一个新的Mongodb,并且在java spring中使用$ lookup遇到问题。

我想在Spring数据中使用这个shell

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

我在Google上找到了,但还没有答案。

布雷克七世:

并非每个“新”功能都会使其立即进入诸如类的抽象层

因此,您需要做的就是定义一个使用该AggregationOperation接口的类,该类将使用直接指定的BSON对象作为其内容:

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);
    }
}

然后,您可以像这样在聚合中使用:

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")
        )
    )
)

该图显示了与内置match()管道助手混合在一起的自定义类

在每个帮助器下发生的所有事情都是将它们序列化为BSON表示形式,例如DBObject无论如何。因此,这里的构造函数只是直接获取对象,然后直接从中返回它.toDBObject(),这是序列化pipline内容时将调用的接口上的标准方法。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章