我不熟悉Stack和MongoDB。我根据其他帖子调整了代码,但不知道哪里出错了。我有三个系列。微生物与活动(1到M)和活动与生物活动(1到M)相关。我想以数组的形式展示从微生物到生物活动的鸟巢。
Microbe collection
{"_id": 1, item: "abc", species: 12, quantity: 2},
{"_id": 2, item: "jkl", species: 20, quantity: 1},
{"_id": 3}
Activities collection
{"_id": 1, code: "MON1003", item: "abc", type: "Monitor", repeat: 120, size: "27", resolution: "1920x1080"},
{"_id": 2, code: "MON1012", item: "abc", type: "Monitor", repeat: 85, size: "23", resolution: "1280x800"},
{"_id": 3, code: "MON1031", item: "jkl", type: "Monitor", repeat: 60, size: "21", resolution: "1920x1080"}
Bio-Activities collection
{"_id": 1, code: "MON1003", description: "bio 1", quantity: 120},
{"_id": 2, code: "MON1003", description: "bio 2", quantity: 80},
{"_id": 3, code: "MON1012", description: "bio 3", quantity: 60},
{"_id": 4, code: "MON1012", description: "bio 4", quantity: 70},
{"_id": 5, code: "MON1012", description: "bio 5", quantity: 170},
{"_id": 6, code: "MON1031", description: "bio 6", quantity: 270}
这是我的代码:
db.microbe.aggregate([
{
$lookup:
{
from: "activities",
localField: "item",
foreignField: "item",
as: "activities"
}
},{
$lookup:
{
from: "bioactivities",
localField: "code",
foreignField: "code",
as: "bioactivities"
}
},{
$unwind: "$activities"
},{
$group: {
_id: "$_id",
item: {$first: "$item"},
species: {$first: "$species"},
quantity: {$first: "$quantity"},
activities: {$push: {
id: "$activities._id",
code: "$activities.code",
item: "$activities.item",
type: "$activities.type",
repeat: "$activities.repeat",
size: "$activities.size",
bioactivities: "$bioactivities"
}
}
}
}
]).pretty()
但我得到的输出显示了空的“生物活性”。我哪里出错了?
{
"_id" : 2,
"item" : "jkl",
"species" : 20,
"quantity" : 1,
"activities" : [
{
"id" : 3,
"code" : "MON1031",
"item" : "jkl",
"type" : "Monitor",
"repeat" : 60,
"size" : "21",
"bioactivities" : [ ]
}
]
}
{
"_id" : 1,
"item" : "abc",
"species" : 12,
"quantity" : 2,
"activities" : [
{
"id" : 1,
"code" : "MON1003",
"item" : "abc",
"type" : "Monitor",
"repeat" : 120,
"size" : "27",
"bioactivities" : [ ]
},
{
"id" : 2,
"code" : "MON1012",
"item" : "abc",
"type" : "Monitor",
"repeat" : 85,
"size" : "23",
"bioactivities" : [ ]
}
]
}
谢谢