简体   繁体   English

Mongo 数据库查询 | 加入| 在两个集合上创建查询

[英]Mongo db query | Join | Create query on two collection

Select leadId count on two collection in Mongo DB在 Mongo DB 中选择两个集合的 leadId 计数

Collection 1: leads集合 1:线索

{
 leadId:"abc123",
 status:"OPENED",
 stage:"start",
 crossSell:
    {
      cc:
         {
            consent:true,
            shown:[{first:true}]
         }
    }
 }

Collection 2: pdata集合二:pdata

{
 activeLeadId:"abc123",
 status:"OPENED",
 details:
    [
        {
            rating:10
        },
        {
            rating:9
        }
    ]
}

Question: Find leadId count from leads collection join with pdata collection based on below conditions问题:根据以下条件从潜在客户集合中查找 leadId 计数并加入 pdata 集合

  1. leads.leadId = pdata.activeleadId and leads.leadId = pdata.activeleadId 和
  2. leads.status = "OPENED" and leads.status = "OPENED" 和
  3. leads.crossSell.cc.consent = true and leads.crossSell.cc.consent = true 和
  4. leads.crossSell.cc.shown[0].first = true and leads.crossSell.cc.shown[0].first = true 和
  5. pdata.details.rating >= 5 pdata.details.rating >= 5

You can try a aggregation query,您可以尝试聚合查询,

  • $match your conditions for leads collection $match您的潜在客户收集条件
  • $lookup with pdata collection, pass leadId to match with pdata $lookuppdata集合,通过leadIdpdata匹配
  • match required conditions for pdata匹配 pdata 所需的条件
  • $limit to return single document, because we don't need that data in response $limit返回单个文档,因为我们不需要该数据作为响应
  • $match condition to check is pdata is not empty要检查的$match条件是pdata不为空
  • $count to get total number of records $count获取记录总数
db.leads.aggregate([
  {
    $match: {
      status: "OPENED",
      "crossSell.cc.consent": true,
      "crossSell.cc.shown.first": true
    }
  },
  {
    "$lookup": {
      "from": "pdata",
      "let": { "leadId": "$leadId" },
      "pipeline": [
        {
          $match: {
            $expr: { $eq: ["$$leadId", "$activeLeadId"] },
            "details.rating": { $gte: 5 }
          }
        },
        { $limit: 1 }
      ],
      "as": "pdata"
    }
  },
  { $match: { pdata: { $ne: [] } } },
  { $count: "count" }
])

Playground操场

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

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