Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb $lookup in Spring data mongo

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

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

I found on Google but no answer yet.

like image 286
Anh Bui Avatar asked Mar 22 '16 02:03

Anh Bui


People also ask

Can I use Spring data JPA with MongoDB?

Yes, DataNucleus JPA allows it, as well as to many other databases.

Which annotation is used to link a MongoDB document with a Spring bean?

The @Id annotation tells the mapper which property you want to use for the MongoDB _id property and the @Indexed annotation tells the mapping framework to call ensureIndex on that property of your document, making searches faster.

Which is better MongoTemplate or MongoRepository?

So I'd say that MongoTemplate is a better option, unless you have a very elaborated POJO model or need the custom queries capabilities of MongoRepository for some reason. Good points/examples. However your race condition example and undesired result can be avoided using @Version to prevent that very scenario.

What is Spring data reactive MongoDB?

The spring-boot-starter-data-mongodb-reactive is a Spring Boot starter for using MongoDB document-oriented database and Spring Data MongoDB Reactive. resources/application.properties. spring.main.banner-mode=off. In the application.


3 Answers

Here is an example:

Collection posts

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

Collection users

{
"_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 query with lookup and match

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

Spring Mongoopration syntax

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();
like image 34
VK321 Avatar answered Oct 07 '22 19:10

VK321


Joining Two Collections with Spring Data MongoDB

Employee Class

class Employee {
    private String _id;
    private String name;
    private String dept_id;
}

Department Class

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

Employee Result Class

public class EmpDeptResult {

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

EmployeeService Class

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());
    }
}
like image 106
Dhiren Chauhan Avatar answered Oct 07 '22 18:10

Dhiren Chauhan


Its too late to answer this, but it might helps other who are facing the same issue. If you are using spring-boot-data-mongodb-2.0 or above version then there is a easy way to implement this.

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);
like image 20
Vivek Singh Avatar answered Oct 07 '22 18:10

Vivek Singh