嗨,我在mongoDb上工作,我有两个收藏集,如下所示:
所有者
[
{
"name": "Johnsons",
"address": "Lambert Street",
"familySize": 4,
"petId": "p153ATjs54"
},
{
"name": "Markinsons",
"address": "Pebble Street",
"familySize": 2,
"petId": "G34hts94"
}
]
宠物
// the foreign key if you may for petId
[
{
"animal_Id": "G34hts94",
"petName": "Oscar",
"preferredPlayToy": "Ball",
"vaccinationInfo": {
"vacId": "a-984KA",
"dosage": 3
}
},
{
"animal_Id": "p153ATjs54",
"petName": "Piggy",
"preferredPlayToy": "Bone",
"vaccinationInfo": {
"vacId": "G-397B",
"dosage": 1
}
}
]
现在,我实际上正在尝试查找所有拥有 preferredPlayToy 为“球”的宠物的主人 以下是我准备中的内容,但似乎无法正确完成:
db.owners.aggregate([
{
$lookup: {
from: 'ms_pets',
localField: 'petId',
foreignField: 'aniId',
as: 'petMaster'
}
},
{
name: 1,
address: 1
'petMasterData': {
$filter:{
input: "$petMaster",
as: "master",
cond: { $eq: [ "$$master.preferredPlayToy", 'ball' ] }
}
}
}
])
如果我可以从Pets表中提取宠物名称和vaccinationInfo作为响应的一部分,那也很好。
预期样本:
{
"name": "Markinsons",
"address": "Pebble Street",
"petId": "G34hts94",
"petMasterData":{
"petName": "Oscar",
"vaccinationInfo": {
"vacId": "a-984KA",
"dosage": 3
}
}
}
答案 0 :(得分:0)
您可以运行$lookup with custom pipeline来应用过滤条件和投影。要将数组转换为单个子文档,您可以使用$unwind,它也会删除owners
和空的petMasterData
db.owners.aggregate([
{
$lookup: {
from: "ms_pets",
let: { pet_Id: "$petId" },
pipeline: [
{ $match: {
$expr: {
$and: [
{ $eq: [ "$$pet_Id", "$animal_Id" ] },
{ $eq: [ "$preferredPlayToy", "Ball" ] } ]
}
}
},
{ $project: { petName: 1, vaccinationInfo: 1, _id: 0 } }
],
as: "petMasterData"
}
},
{ $unwind: "$petMasterData" }
])