简体   繁体   English

在 mongodb / mongoose 中使用条件查找“来自”

[英]Using conditional lookup 'from' in mongodb / mongoose

Is it possible to use conditional lookup source('from'),in mongodb or mongoose like as follows是否可以在 mongodb 或 mongoose 中使用条件查找源('from'),如下所示

 Collection.aggregate([
      {
        '$match': {
          'receivers.user': new ObjectId('..........')
        }
      }, {
        '$lookup': {
          'from': $switch: {
   type: [
      { case: 101, then: collection1 },
      { case: 102, then: collection2 },
   ]
}, 
          'localField': 'data.on_behalf', 
          'foreignField': '_id', 
          'as': 'data.on_behalf'
        }
      }, {
        '$unwind': {
          'path': '$data.on_behalf', 
          'preserveNullAndEmptyArrays': true
        }
      }
    ])

I want to switch my lookup collection according to the type value..我想根据类型值切换我的查找集合..

If you just have 2 cases, you can use conditional operator to specify the collection to lookup from:如果您只有 2 种情况,则可以使用条件运算符指定要从中查找的集合:

 Collection.aggregate([
  ..., 
  {
    '$lookup': {
      'from': type == 101 ? 'collection1' : 'collection2', 
      'localField': 'data.on_behalf', 
      'foreignField': '_id', 
      'as': 'data.on_behalf'
    }
  },...

Or if you have more cases, you can create a switch statement outside to specify the collection then pass it to aggregate.或者,如果您有更多案例,您可以在外部创建一个 switch 语句来指定集合,然后将其传递给聚合。 Example:例子:

let collection_to_lookup;
switch(type) {
  case 101: collection_to_lookup = "collection1"; break;
  case 102: collection_to_lookup = "collection2"; break;
  ...
  default: collection_to_lookup = "collection1"; break;
}

Collection.aggregate([
  ..., 
  {
    '$lookup': {
      'from': collection_to_lookup, 
      'localField': 'data.on_behalf', 
      'foreignField': '_id', 
      'as': 'data.on_behalf'
    }
  },...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM