Mongodb $lookup in Spring data mongo

spring data mongodb aggregation count
mongodb lookup
spring data mongodb aggregation with query
join two collections in mongodb using spring data
spring data mongodb aggregation addtoset
mongodb lookup array
mongodb nested lookup
spring mongo data aggregation

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.


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

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

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

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 Data MongoDB Lookup with Pipeline Aggregation, This will allow me to use pipeline within a $lookup which is not to pass a custom JSON query into our mongodb spring implementation, mongoTemplate​.aggregate(aggregation, FulfillmentChannel.class); return results. Specifies the field from the documents input to the $lookup stage. $lookup performs an equality match on the localField to the foreignField from the documents of the from collection. If an input document does not contain the localField, the $lookup treats the field as having a value of null for matching purposes.


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

LookupOperation (Spring Data MongoDB 3.0.1.RELEASE API), org.springframework.data.mongodb.core.aggregation.LookupOperation Encapsulates the aggregation framework $lookup -operation. We recommend to use  Spring Data MongoDB stores the type information as the last field for the actual root class as well as for the nested type (because it is complex and a subtype of Contact). So, if you now use mongoTemplate.findAll(Object.class, "sample"), you can find out that the document stored is a Sample instance.


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

Spring Data MongoDB: Projections and Aggregations, With Spring Data MongDB, projections can be used both with MongoTemplate and MongoRepository. Before we move further, let's look at the  The Spring Data MongoDB project applies core Spring concepts to the development of solutions using the MongoDB document style data store. We provide a "template" as a high-level abstraction for storing and querying documents. You will notice similarities to the JDBC support in the Spring Framework.


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

$lookup (aggregation), Performs a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing. To each input  Subscribe to this blog. MongoDB Join/Aggregate Query Returning Silence in Console. 0


Can use below to join 3 Collections

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

mongoDb aggregation to Spring data, In short, you'll use `MongoTemplate.aggregate(..)` and pass in the AggregateOperation you want to run. You can use `Aggregation. Changed in version 4.0.3: By defining the zones and the zone ranges before sharding an empty or a non-existing collection, the shard collection operation creates chunks for the defined zone ranges as well as any additional chunks to cover the entire range of the shard key values and performs an initial chunk distribution based on the zone ranges.


Spring Boot Integration, Spring Boot Integration - MongoDB Integration 4 (MongoDB grouping mongodb multitable queries operate using the Aggregation.lookup API.The four mongoTemplate.aggregate(noRepeatAggregation2, OrderVo.class);  Replaces the input document with the specified document. The operation replaces all existing fields in the input document, including the _id field. You can promote an existing embedded document to the top level, or create a new document for promotion (see example).


How to make aggregations with lookups to make joins , with the current collection, and which fields that should match. Upgrade MongoDB Community to MongoDB Enterprise. Upgrade to MongoDB Enterprise (Standalone) Upgrade to MongoDB Enterprise (Replica Set) Upgrade to MongoDB Enterprise (Sharded Cluster) Verify Integrity of MongoDB Packages; The mongo Shell. Configure the mongo Shell; Access the mongo Shell Help; Write Scripts for the mongo Shell; Data Types in


MongoDB Aggregation Stages Operator - $unwind, , it is very much easy since it is a schema less database. This page provides examples of operations that query for null values using the com.mongodb.reactivestreams.client.MongoCollection.find method in the MongoDB Java Reactive Streams Driver. The examples on this page use the inventory collection. To populate the inventory collection, run the following: