我有两个集合:一个叫做places和type_places。place关联了一种place类型(type_places),这可以将其中的一些对象(objects数组)关联起来。
type_places
{
"_id": "5fbc7cc705253c2da482023f",
"type_place": "office",
"objects": [
{
"_id": "5fbc7cc705253c2da48202saw",
"name": "chair"
},
{
"_id": "5fbc7cc705253c2da4820242",
"name": "table"
},
{
"_id": "5fbc7cc705253c2da482025f",
"name": "desktop"
}
]
}
places
{
"_id": "5fbc7cc705253c2da482025f",
"place": "Room 5",
"type_place_id": "5fbc7cc705253c2da482023f", /*"office"*/
"type_place_objects": [
{
"_id": "5fbc7cc705253c2da48202saw", /*chair*/
"quantify": 4
},
{
"_id": "5fbc7cc705253c2da482025f", /*desktop*/
"quantify": 2
}
]
}然后我希望当我查询一个place时,这个查询会显示我所咨询的place,它是什么样的地方(type_place),以及它有什么样的objects。
期望的产出:
{
"_id": "5fbc7cc705253c2da482023f",
"place": "Room 5",
"type_place_objects": [
{
"_id": "5fbc7cc705253c2da48202saw",
"name": "chair",
"quantify": 4
},
{
"_id": "5fbc7cc705253c2da482025f",
"name": "desktop",
"quantify": 2
}
]
}我正在尝试,但不起作用:
place.aggregate(
[
{
"$match": {"place":"Room 5"}
},
{
"$lookup": {
"from": "type_place",
"localField": "type_place_id",
"foreignField": "_id",
"as": "type_place_objects"
}
},
{
"$sort": {
"_id": -1
}
},
{
"$project": {
"_id":1,
"place":1,
"type_place_objects": 1
}
}
])怎么才能修好呢?
发布于 2020-11-27 07:55:21
有很多种方法,其中一种方法是在您已经尝试过的情况下使用$lookup
db.place.aggregate([
{ "$match": { "place": "Room 5" } },
{ $unwind: "$type_place_objects" },
{
"$lookup": {
"from": "type_place",
"let": { tpo: "$type_place_objects._id" },
"pipeline": [
{ $unwind: "$objects" },
{
$match: {
$expr: {
$eq: [ "$objects._id", "$$tpo" ]
}
}
}
],
"as": "join"
}
},
{
$addFields: {
"join": { "$arrayElemAt": [ "$join", 0]
}
}
},
{
$addFields: { "type_place_objects.name": "$join.objects.name" }
},
{
$group: {
_id: "$_id",
place: { $first: "$place" },
type_place_objects: { "$addToSet": "$type_place_objects" }
}
}
])Working 蒙戈游乐场
https://stackoverflow.com/questions/65032621
复制相似问题