Dynamic from in $lookup

I am trying to see if i can change the from in the $lookup or rearrange my query to somehow retrieve from three different collections. So far i have managed to set up the query like so:

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) ... )

The $match and then $project pipeline stages return a result with the following properties:

collection:"arxiv"
id_int:0

The collection value will always be one of three arxiv, crossref or pmc_test. Therefore i’d like my $lookup from to use this property value programmatically as opposed having it hard coded.

Thanks

Hi @natedeploys,

Currently the from is accepting a collection namespace, not aggregation expressions.

However, you could still do this programmatically by running two phase query on the application code. First, perform a query to find out which collection, then use the collection value into an aggregation pipeline.

Regards,
Wan.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.