Spring数据mongo中的Mongodb $ lookup [英] Mongodb $lookup in Spring data mongo

查看:1794
本文介绍了Spring数据mongo中的Mongodb $ lookup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新的Mongodb,我遇到了使用java spring查找$的问题。

I'm a new Mongodb and I have a problem with $lookup with java spring.

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

I would like to use this shell in Spring data

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

我在Google上找到但尚无答案。

I found on Google but no answer yet.

推荐答案

并非所有新功能都会立即进入抽象图层 spring-mongo 等图层。

Not every "new" feature makes it immediately into abstraction layers such as spring-mongo.

所以你需要做的就是定义一个使用 AggregationOperation 接口的类,而不是BSON对象指定了di直接因为它的内容:

So instead, all you need do is define a class that uses the AggregationOperation interface, which will instead take a BSON Object specified directly as it's content:

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

然后你可以在你的聚合中使用这样的:

Then you can use in your aggregation like this:

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

其中显示自定义类与内置<$混合c $ c> match()管道帮助器。

Which shows the custom class mixed with the built in match() pipeline helper.

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

All that happens underneath each helper is that they serialize to a BSON representation such as with DBObject anyway. So the constructor here just takes the object directly, and returns it directly from .toDBObject(), which is the standard method on the interface that will be called when serializing the pipline contents.

这篇关于Spring数据mongo中的Mongodb $ lookup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆