$ lookup中的动态来源

问题描述 投票:0回答:1

我正在尝试查看是否可以更改$ lookup中的from或重新排列我的查询以某种方式从三个潜在的集合中检索。到目前为止,我已经设法像这样设置查询:

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 from

以编程方式使用此属性值,而不是对其进行硬编码。'$lookup': { 'from': 'arxiv' or 'crossref' or 'pmc_test', // Dynamic based on result ... }
谢谢

编辑

id_int将被传递而集合不会被传递,这就是为什么要对搜索集合进行查询的原因。
mongodb mongodb-query nosql node-mongodb-native
1个回答
0
投票
可悲的是,目前尚无法实现,它here上有一个开放功能要求,因此,您可以随时跟踪它。

现在认为您有两个选择。

  1. 将您的呼叫分为2个查询,然后在代码中添加一些逻辑,这是我个人所建议的。
  2. 使用此聚合查找所有3个馆藏:

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" } } } } ])

您可能已经注意到管道并不完全性感,如果您不在乎最终结果中的字段名称,则可以将其大部分转储。
© www.soinside.com 2019 - 2024. All rights reserved.