Mongodb $查找Spring数据mongo

时间:2016-03-22 02:35:09

标签: java mongodb spring-mongo

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

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

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

我在Google上发现但尚无答案。

5 个答案:

答案 0 :(得分:6)

不是每个"新" feature会立即进入抽象层,例如

因此,您需要做的就是定义一个使用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内容时将被调用的接口上的标准方法。

答案 1 :(得分:6)

使用Spring Data MongoDB加入两个集合

员工类

class Employee { private String _id;enter code here private String name; private String dept_id; }

系类

class Department { private String _id; private String dept_name; }

员工结果类 ` 公共类EmpDeptResult {

private String _id;
private String name;
private List<Object> departments;

}`

EmployeeSerivce `public class EmployeeService {

@Autowired
private MongoTemplate mongoTemplate;

private Logger LOGGER = LoggerFactory.getLogger(EmployeeService.class);

public void lookupOperation(){
    LookupOperation lookupOperation = LookupOperation.newLookup()
                        .from("Department")
                        .localField("dept_id")
                        .foreignField("_id")
                        .as("departments");

    Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(Criteria.where("_id").is("1")) , lookupOperation);
    List<EmpDeptResult> results = mongoTemplate.aggregate(aggregation, "Employee", EmpDeptResult.class).getMappedResults();
    LOGGER.info("Obj Size " +results.size());
}

}`

答案 2 :(得分:3)

以下是一个例子:

收藏帖子

{
"_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查询

db.users.aggregate([
{
  $lookup:
    {
      from: "users",
      localField: "userid",
      foreignField: "authors",
      as: "post"
    }
  },
  {
     $match: { "post": { $ne: [] } }
  }
]).pretty()

Spring 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();

答案 3 :(得分:2)

现在回答这个问题为时已晚,但这可能会帮助其他面临相同问题的人。 如果您使用的是spring-boot-data-mongodb-2.0或更高版本,则有一种简便的方法可以实现此目的。

AggregationOperation match = Aggregation.match(Criteria.where("username").is("user001")));
AggregationOperation query = Aggregation.lookup("NewfeedContent", "content.contentId", "_id", "NewfeedContent");
// If you want to unwind
//AggregationOperation unwind = Aggregation.unwind("Patient");
Aggregation agr = Aggregation.newAggregation(query, match, unwind);
AggregationResults<Document> result = springTemplate.aggregate(agr, "CollectionName", Document.class);

答案 4 :(得分:0)

可以在下面使用以加入3个收藏集

MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

DB db = mongoClient.getDB( "DBname" );

BasicDBObject query = BasicDBObject.parse("{$match:{_id:61188}},\n" +
        "   {\n" +
        "     $lookup:\n" +
        "       {\n" +
        "         from: \"CustomerDetails\",\n" +
        "         localField: \"supplierId\",\n" +
        "         foreignField: \"supplierId\",\n" +
        "         as: \"newfield\"\n" +
        "       }\n" +
        "  }\n" +
        "  ,  {\n" +
        "     $lookup:\n" +
        "       {\n" +
        "         from: \"ItemDetails\",\n" +
        "         localField: \"supplierId\",\n" +
        "         foreignField: \"supplierId\",\n" +
        "         as: \"newfield\"\n" +
        "       }\n" +
        "  }");

AggregationOutput dumps = db.getCollection("HeaderInfo").aggregate(query);

System.out.println("result="+dumps.results());