我试图在两个集合之间的MongoDb上执行查找,其中一个字段作为键-值对属性,在这里我只能选择key作为本地字段参数。
Json示例:
下方json的键
{ "distributions" : {
"5cf88" : "5d023d4aa",
"5cfaca42e" : "5d0093a",
"5d023d490d" : "5d22abc69093a"
}
}
以下json的_id字段:
{
"_id" : "5d22abc69093a",
"activatedBy" : {
"id" : "5bc53813055aec",
"name" : "Test1",
"roles" : [
"root"
]
}
}
查询查询:
$lookup: {
from: 'collecection1',
localField: 'distributions.key',
foreignField: '_id',
as: 'Join'
}
如何获取它们的键形式分布以用于查找,因为我只需要键of作为连接参数?
答案 0 :(得分:1)
如何根据我的需要获取它们的关键表单分布以用于查找 唯一的键作为我的连接参数?
此聚合查询可以使用$objectToArray聚合运算符来实现:
db.collection1.aggregate( [
{ $addFields: { fieldNameValues: { $objectToArray: "$$ROOT" } } },
{ $unwind: "$fieldNameValues" },
{ $match: { $expr: { $eq: [ { $type: "$fieldNameValues.v" } , "object" ] } } },
{ $addFields: { objs: { $objectToArray: "$fieldNameValues.v" } } },
{ $unwind: "$objs" },
{ $project: { distributions: "$objs" } },
{ $lookup: {
from: 'collection2',
localField: 'distributions.v',
foreignField: '_id',
as: 'Join'
}
}
] )
其中:
collection1 :
{ "distributions" : {
"5cf88" : "5d023d4aa",
"5cfaca42e" : "5d0093a",
"5d023d490d" : "5d22abc69093a"
}
}
collection2 :
{
"_id" : "5d22abc69093a",
"activatedBy" : {
"id" : "5bc53813055aec",
"name" : "Test1",
"roles" : [
"root"
]
}
}