簡體   English   中英

使用 mongoose 對 collections 進行條件連接

[英]Conditional joins on collections using mongoose

我是 mongoDB 的新手,我正在嘗試對其進行以下 SQL 查詢。 但到目前為止找不到任何有用的東西。 誰能告訴等效的 mongoose 查詢

select * from interviews
inner join candidate on interviews.clientId = candidate._id
inner join billing on appointment._id = billing.appointmentId
where  ('
  interviews.status= "upcoming",
  interviews.startTime= "2017-01-01",
  candidate.clientAgeGroup= "adult",
  candidate.candidatetatus= "new",
  billing.paymentStatus= "paid"
  ')

到目前為止我得到的是以下

 const [result, err] = await of(Interview.find({ ...filterQuery }).limit(perPage)
   .skip(perPage * page)
   .sort({
     startTime: 'asc'
   })
   .populate([{ path: 'candidateId', model: 'Candidate', select: 'firstName status avatar' },
   { path: 'billingId', model: 'Billing', select: "status" }]));

更新

我有以下名稱和導出方案

//interview.model.js => mongodb show name as interview
module.exports = mongoose.model('Interview', interviewSchema);
//candidate.model.js => mongodb show name as candidate
module.exports = mongoose.model('Candidate', candidateSchema);

您可以使用match過濾掉包含在結果數組中的對象,但如果找不到任何對象,它仍然會返回 null 值。 所以相比之下,這類似於 sql 左連接。

const [result, err] = await of(Interview.find({ ...filterQuery }).limit(perPage)
   .skip(perPage * page)
   .sort({
     startTime: 'asc'
   })
   .populate([{ path: 'candidateId', model: 'Candidate', select: 'firstName status avatar', match: {clientAgeGroup: "adult", candidatetatus: "new"} },
   { path: 'billingId', model: 'Billing', select: "status", match: {paymentStatus: "paid"} }]));

另請參閱https://mongoosejs.com/docs/populate.html#query-conditions

如果您需要嚴格的內部連接,那么您可以使用 mongodb 聚合管道。

Interview.aggregate([
  {
    "$match": {
      status: "upcoming",
      startTime: "2017-01-01",
    }
  },
  {
    '$lookup': {
      'from': 'candidates', // this should be your collection name for candidates.
      'localField': 'candidateId', // there should be an attribute named candidateId in interview model that refer to candidate collection
      'foreignField': '_id',
      'as': 'candidates'
    }
  }, {
    '$match': {
      'candidates.clientAgeGroup': "adult",
      'candidates.candidatetatus': "new"
    }
  },
  {
    '$lookup': {
      'from': 'billing', // this should be your collection name for billing.
      'localField': 'billingId', // there should be an attribute named billingId in interview model that refer to billing collection
      'foreignField': '_id',
      'as': 'billing'
    }
  }, {
    '$match': {
      'billing.paymentStatus': "paid"
    }
  },
  { "$sort": { startTime: 1 } },
  { "$limit": perPage },
  { "$skip": perPage * page }
])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM