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).getM