英文:
How can I join two collections spring-data-mongodb?
问题
Here are the translated parts:
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
If you want to display the query result using Query in Java, you would need to write Java code to execute the SQL query against your database and retrieve the results.
英文:
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
答案1
得分: 1
1. 聚合管道中的聚合方法
2. 使用Lookup操作连接Room和RoomType集合
3. room集合的LocalField
4. RoomType集合的ForeignField
5. $unwind: 是可选的,主要用于展平结果数组
英文:
db.Room.aggregate([
{
$lookup: {
from: "RoomType".
localField: "roomtypeId",
foreignField: "_id",
as: "roomType"
}
},
{
$unwind: "$roomType"
}
])
- Aggregate method for aggregation pipeline
- Lookup used to join the collection Room and RoomType
- LocalField for the room collection
- ForeignField for RoomType collection.
- $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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论