我试图看看是否可以在$lookup中更改中的,或者重新安排查询,以便从三个潜在的集合中检索。到目前为止,我已经成功地设置了这样的查询:
const search = db.collection("search");
search.aggregate([
{
'$match': {
'id_int': 0
}
}, {
'$project': {
'_id': 0,
'collection': 1,
'id_int': 1
}
}, {
'$lookup': {
'from': 'arxiv',
'localField': 'id_int',
'foreignField': 'id_int',
'as': 'arxiv'
}
}
], function(err, cursor) ... )$match然后$project管道阶段返回具有以下属性的结果:
collection:"arxiv"
id_int:0 集合值将始终是三个arxiv、crossref或pmc_test之一。因此,我希望我的$lookup (来自)以编程方式使用这个属性值,而不是硬编码。
'$lookup': {
'from': 'arxiv' or 'crossref' or 'pmc_test', // Dynamic based on result
...
}谢谢
编辑
id_int将被传入,而集合将不会被传递,这就是为什么对搜索集合进行查询的原因。
发布于 2020-03-12 08:01:12
遗憾的是,目前这是不可能的,这里上有一个开放的特性请求,所以如果您愿意,可以随时跟踪它。
现在以为你有两个选择。
search.aggregate([
{
'$match': {
'id_int': 0
}
},
{
'$project': {
'_id': 0,
'collection': 1,
'id_int': 1
}
},
{
"$facet": {
"arxiv": [
{
"$lookup": {
"from": "arxiv",
"localField": "id_int",
"foreignField": "id_int",
"as": "arxiv"
}
}
],
"crossref": [
{
"$lookup": {
"from": "crossref",
"localField": "id_int",
"foreignField": "id_int",
"as": "crossref"
}
}
],
"pmc_test": [
{
"$lookup": {
"from": "pmc_test",
"localField": "id_int",
"foreignField": "id_int",
"as": "pmc_test"
}
}
]
}
},
{
"$addFields": {
"newRoot": [
{
"k": "$collection",
"v": {
"$cond": [
{
"$eq": [
"$collection",
"arxiv"
]
},
"$arxiv",
{
"$cond": [
{
"$eq": [
"$collection",
"crossref"
]
},
"$crossref",
"$pmc_test"
]
}
]
}
},
{
"k": "collection", "v": "$collection"
},
{
"k": "id_int", "v": "$id_int"
}
]
}
},
{
"$replaceRoot": {
"newRoot": {
"$arrayToObject": {
"$concatArrays": "$newRoot"
}
}
}
}
])正如您可能已经注意到的,管道并不完全性感,如果您不关心字段名的最终结果,您可以转储它的大部分。
https://stackoverflow.com/questions/60642230
复制相似问题