0

Collection:

Room

{
    "_id" : ObjectId("6461eb7c1cefe2b485d4ca2e"),
    "AgentId" : "5e7a1caaa08a49ff4d029bbd",
    "roomName" : "My Room101",
    "note" : "note abc",
    "roomStatus" : "Empty",
    "roomTypeId" : "6461db161cefe2b485d4ca1e",
    "createdBy" : "Super Administrator",
    "createdAt" : ISODate("2023-05-15T08:00:00.000+0000"),
    "updatedBy" : "Super Administrator",
    "updatedAt" : ISODate("2023-05-15T08:00:00.000+0000"),
    "isDeleted" : false
}

RoomType

  {
    "_id" : ObjectId("6461db161cefe2b485d4ca1e"),
    "roomTypeName" : "VIP 1",
    "note" : "note xyz",
    "createdBy" : "Super Administrator",
    "createdAt" : ISODate("2023-05-15T08:00:00.000+0000"),
    "updatedBy" : "Super Administrator",
    "updatedAt" : ISODate("2023-05-15T08:00:00.000+0000"),
    "isDeleted" : false
}

in SQL:

select * from Room r inner join RoomType rt on r.roomTypeId=rt._id

I want to display query result using Query in Java

Pnmtriet
  • 15
  • 5
  • Kindly refer to following : https://stackoverflow.com/questions/2350495/how-do-i-perform-the-sql-join-equivalent-in-mongodb?rq=2 – psybrg May 17 '23 at 05:29

1 Answers1

1
db.Room.aggregate([
 {
 $lookup: {
  from: "RoomType".
  localField: "roomtypeId",
  foreignField: "_id",
  as: "roomType"
 }
 },
{
 $unwind: "$roomType"
 }
])
  1. Aggregate method for aggregation pipeline
  2. Lookup used to join the collection Room and RoomType
  3. LocalField for the room collection
  4. ForeignField for RoomType collection.
  5. $unwind: is optional mainly used to flatten the resulting array

In java,

LookupOperation lookup = LookupOperation.newLookup()
  .from("roomTypes")
  .localField("roomtypeId")
  .foreignField("_id")
  .as("roomType");

Aggregation aggregation = Aggregation.newAggregation(
  Aggregation.match('add condition'), lookup );

mongoTemplate.aggregate(aggregation, "rooms", 
Room.class).getMappedResults();
JavaLearner1
  • 607
  • 2
  • 8
  • 21
  • If in SQL it's like this: select * from Room r inner join RoomType rt on r.roomTypeId=rt._id where rt._id = 'abc123' What is a query in MongoDB? – Pnmtriet May 25 '23 at 08:44