【问题标题】:Mongodb Count on multiple sub arraysMongodb 对多个子数组进行计数
【发布时间】:2017-01-08 10:32:08
【问题描述】:

根据公司名称计算所有协议、联系人和组的数量。笔记。协议和联系人是对象数组

这是我的数据的示例文档:

{
    "_id" : ObjectId("57c7bd8f51666ac615bc837d"),
    "ITBCompanyId" : 2296,
    "updatedAt" : ISODate("2016-09-01T05:38:02.843Z"),
    "createdAt" : ISODate("2016-09-01T05:33:03.604Z"),
    "identifier" : "SOU10",
    "name" : "Source One Rehabilitation",
    "addressLine2" : null,
    "city" : "Plano",
    "state" : "TX",
    "zip" : "75024",
    "faxNumber" : "",
    "territoryId" : "11",
    "marketId" : null,
    "accountNumber" : "Source One Rehabilitation",
    "dateAcquired" : ISODate("2014-09-15T04:00:00.000Z"),
    "parentCompany" : null,
    "annualRevenue" : null,
    "numberOfEmployees" : null,
    "ownershipType" : null,
    "deletedBy" : null,
    "orgId" : "1",
    "deletedAt" : null,
    "_info" : {
        "lastUpdated" : ISODate("2016-09-01T05:12:32.000Z"),
        "updatedBy" : "LabTechInt"
    },
    "whois" : [],
    "configuration" : [],
    "contact" : [ 
        {
            "mobileGuid" : "6435d4c0-12fa-41d1-9db0-e4f9b1b4e7b2",
            "presence" : null,
            "gender" : null,
            "title" : null,
            "country" : null,
            "zip" : "75024",
            "state" : "TX",
            "city" : "Plano",
            "addressLine2" : null,
            "lastName" : null,
            "firstName" : "Dee Williams",
            "id" : 821,
            "_id" : ObjectId("57c7beba51666ac615bc8576"),
            "communicationItems" : [],
            "customFields" : null,
            "relationship" : {
                "name" : null,
                "id" : 0
            }
        }, 
        {
            "id" : 829,
            "firstName" : "Jesy",
            "lastName" : "Leon",
            "addressLine2" : null,
            "city" : "Plano",
            "state" : "TX",
            "zip" : "75024",
            "country" : null,
            "title" : null,
            "gender" : null,
            "presence" : null,
            "mobileGuid" : "2b0754c1-c256-4063-9cea-c40f9ca77084",

            "_id" : ObjectId("57c7beba51666ac615bc857d"),
            "communicationItems" : [ 
                {
                    "communicationType" : "Email",
                    "defaultFlag" : true,
                    "extension" : null,
                    "type" : {
                        "_info" : null,
                        "name" : "Email",
                        "id" : 1
                    },
                    "id" : 45587
                }, 
                {
                    "communicationType" : "Phone",
                    "defaultFlag" : true,
                    "extension" : null,
                    "value" : "9728012190",
                    "type" : {
                        "_info" : null,
                        "name" : "Direct",
                        "id" : 2
                    },
                    "id" : 45590
                }
            ],
            "customFields" : null,
            "company" : {
                "id" : "19390",
                "name" : "Source One Rehabilitation",
            },
            "relationship" : {
                "id" : 0,
                "name" : null
            }
        }, 
        {
            "id" : 850,
            "firstName" : "Dr.",
            "lastName" : "Gabriel",
            "addressLine2" : null,
            "city" : "Plano",
            "state" : "TX",
            "zip" : "75024",
            "country" : null,
            "title" : null,
            "gender" : null,
            "presence" : null,
            "mobileGuid" : "8c833a31-369d-4499-87cb-b5598826e653",
            "_id" : ObjectId("57c7beba51666ac615bc8592"),
            "communicationItems" : [ 
                {
                    "communicationType" : "Email",
                    "defaultFlag" : true,
                    "extension" : null,
                    "type" : {
                        "_info" : null,
                        "name" : "Email",
                        "id" : 1
                    },
                    "id" : 45627
                }, 
                {
                    "communicationType" : "Phone",
                    "defaultFlag" : true,
                    "extension" : null,
                    "value" : "9728012190",
                    "type" : {
                        "_info" : null,
                        "name" : "Direct",
                        "id" : 2
                    },
                    "id" : 45628
                }
            ],
            "customFields" : null,
            "relationship" : {
                "id" : 0,
                "name" : null
            }
        }
    ],
    "agreement" : [ 
        {
            "periodType" : null,
            "billAmount" : "0",
            "billTermsId" : 12,
            "billOneTimeFlag" : false,
            "billCycleId" : "2",
            "expiredDays" : "0",
            "coverAgreementExpense" : false,
            "coverAgreementProduct" : false,
            "coverAgreementTime" : true,
            "oneTimeFlag" : false,
            "applicationUnlimitedFlag" : true,
            "applicationCycle" : "CalendarMonth",
            "applicationLimit" : "0",
            "applicationUnits" : "Hours",
            "internalNotes" : "",
            "workOrder" : "",
            "slaId" : "2",
            "reasonCancelled" : "",
            "dateCancelled" : null,
            "cancelledFlag" : false,
            "noEndingDateFlag" : false,
            "endDate" : "2016-01-31T05:00:00Z",
            "startDate" : "2015-02-01T05:00:00Z",
            "businessUnitId" : 2,
            "locationId" : "11",
            "customerPO" : "",
            "parentAgreementId" : null,
            "name" : "Complete Managed Services Agreement",
            "id" : "109",
            "_id" : ObjectId("57c7bd9051666ac615bc83e3"),
            "_info" : {
                "updatedBy" : "Ali            ",
                "lastUpdated" : ISODate("2016-05-12T20:55:21.000Z")
            },
            "workType" : {
                "_info" : null,
                "name" : "Remote",
                "id" : "3"
            },
            "workRole" : {
                "_info" : null,
                "name" : "Support Engineer",
                "id" : "5"
            },
            "contact" : {
                "name" : "Heather B",
                "id" : "539"
            },
            "agreementType" : {
                "name" : "Complete Managed Services",
                "id" : "19"
            }
        }, 
        {
            "id" : "121",
            "name" : "Complete Managed Services: IMV",
            "parentAgreementId" : null,
            "customerPO" : "",
            "locationId" : "11",
            "businessUnitId" : 2,
            "startDate" : "2016-03-01T05:00:00Z",
            "endDate" : null,
            "noEndingDateFlag" : true,
            "cancelledFlag" : false,
            "dateCancelled" : null,
            "reasonCancelled" : "",
            "slaId" : "2",
            "workOrder" : "",
            "internalNotes" : "",
            "applicationUnits" : "Hours",
            "applicationLimit" : "0",
            "applicationCycle" : "CalendarMonth",
            "applicationUnlimitedFlag" : true,
            "oneTimeFlag" : false,
            "coverAgreementTime" : true,
            "coverAgreementProduct" : false,
            "coverAgreementExpense" : false,
            "expiredDays" : "0",
            "billCycleId" : "2",
            "billOneTimeFlag" : false,
            "billTermsId" : 12,
            "billAmount" : "0",
            "periodType" : null,
            "_id" : ObjectId("57c7bd9051666ac615bc83fa"),
            "_info" : {
                "lastUpdated" : ISODate("2016-05-12T22:11:59.000Z"),
                "updatedBy" : "Ali            "
            },
            "workType" : {
                "id" : "3",
                "name" : "Remote",
                "_info" : null
            },
            "workRole" : {
                "id" : "5",
                "name" : "Support Engineer",
                "_info" : null
            },
            "contact" : {
                "id" : "810",
                "name" : "Jarrod Rogers"
            },
            "agreementType" : {
                "id" : "19",
                "name" : "Complete Managed Services"
            }
        }, 
        {
            "id" : "122",
            "name" : "Complete Managed Servicess: FTW",
            "parentAgreementId" : null,
            "customerPO" : "",
            "locationId" : "11",
            "businessUnitId" : 2,
            "startDate" : "2016-03-01T05:00:00Z",
            "endDate" : null,
            "noEndingDateFlag" : true,
            "cancelledFlag" : false,
            "dateCancelled" : null,
            "reasonCancelled" : "",
            "slaId" : "2",
            "workOrder" : "",
            "internalNotes" : "",
            "applicationUnits" : "Hours",
            "applicationLimit" : "0",
            "applicationCycle" : "CalendarMonth",
            "applicationUnlimitedFlag" : true,
            "oneTimeFlag" : false,
            "coverAgreementTime" : true,
            "coverAgreementProduct" : false,
            "coverAgreementExpense" : false,
            "expiredDays" : "0",
            "billCycleId" : "2",
            "billOneTimeFlag" : false,
            "billTermsId" : 12,
            "billAmount" : "0",
            "periodType" : null,
            "_id" : ObjectId("57c7bd9051666ac615bc83fd"),
            "_info" : {
                "lastUpdated" : ISODate("2016-05-12T22:14:29.000Z"),
                "updatedBy" : "Ali            "
            },
            "workType" : {
                "id" : "3",
                "name" : "Remote",
                "_info" : null
            },
            "workRole" : {
                "id" : "5",
                "name" : "Support Engineer",
                "_info" : null
            },
            "contact" : {
                "id" : "810",
                "name" : "Jarrod Rogers"
            },
            "agreementType" : {
                "id" : "19",
                "name" : "Complete Managed Services"
            }
        }, 
        {
            "id" : "123",
            "name" : "Complete Managed Servicess: SC",
            "parentAgreementId" : null,
            "customerPO" : "",
            "locationId" : "11",
            "businessUnitId" : 2,
            "startDate" : "2016-03-01T05:00:00Z",
            "endDate" : null,
            "noEndingDateFlag" : true,
            "cancelledFlag" : false,
            "dateCancelled" : null,
            "reasonCancelled" : "",
            "slaId" : "2",
            "workOrder" : "",
            "internalNotes" : "",
            "applicationUnits" : "Hours",
            "applicationLimit" : "0",
            "applicationCycle" : "CalendarMonth",
            "applicationUnlimitedFlag" : true,
            "oneTimeFlag" : false,
            "coverAgreementTime" : true,
            "coverAgreementProduct" : false,
            "coverAgreementExpense" : false,
            "expiredDays" : "0",
            "billCycleId" : "2",
            "billOneTimeFlag" : false,
            "billTermsId" : 12,
            "billAmount" : "0",
            "periodType" : null,
            "_id" : ObjectId("57c7bd9051666ac615bc83ff"),
            "_info" : {
                "lastUpdated" : ISODate("2016-05-12T22:13:59.000Z"),
                "updatedBy" : "Ali            "
            },
            "workType" : {
                "id" : "3",
                "name" : "Remote",
                "_info" : null
            },
            "workRole" : {
                "id" : "5",
                "name" : "Support Engineer",
                "_info" : null
            },
            "contact" : {
                "id" : "810",
                "name" : "Jarrod Rogers"
            },
            "agreementType" : {
                "id" : "19",
                "name" : "Complete Managed Services"
            }
        }, 
        {
            "id" : "124",
            "name" : "Complete Managed Servicess: Psych",
            "parentAgreementId" : null,
            "customerPO" : "",
            "locationId" : "11",
            "businessUnitId" : 2,
            "startDate" : "2016-03-01T05:00:00Z",
            "endDate" : "2016-05-31T04:00:00Z",
            "noEndingDateFlag" : false,
            "cancelledFlag" : false,
            "dateCancelled" : null,
            "reasonCancelled" : "",
            "slaId" : "2",
            "workOrder" : "",
            "internalNotes" : "",
            "applicationUnits" : "Hours",
            "applicationLimit" : "0",
            "applicationCycle" : "CalendarMonth",
            "applicationUnlimitedFlag" : true,
            "oneTimeFlag" : false,
            "coverAgreementTime" : true,
            "coverAgreementProduct" : false,
            "coverAgreementExpense" : false,
            "expiredDays" : "0",
            "billCycleId" : "2",
            "billOneTimeFlag" : false,
            "billTermsId" : 12,
            "billAmount" : "0",
            "periodType" : null,
            "_id" : ObjectId("57c7bd9051666ac615bc8402"),
            "_info" : {
                "lastUpdated" : ISODate("2016-06-01T16:48:03.000Z"),
                "updatedBy" : "Ali            "
            },
            "workType" : {
                "id" : "3",
                "name" : "Remote",
                "_info" : null
            },
            "workRole" : {
                "id" : "5",
                "name" : "Support Engineer",
                "_info" : null
            },
            "contact" : {
                "id" : "810",
                "name" : "Jarrod Rogers"
            },
            "agreementType" : {
                "id" : "19",
                "name" : "Complete Managed Services"
            }
        }, 
        {
            "id" : "125",
            "name" : "Managed Services Agreement",
            "parentAgreementId" : null,
            "customerPO" : "",
            "locationId" : "11",
            "businessUnitId" : 2,
            "startDate" : "2016-06-01T04:00:00Z",
            "endDate" : null,
            "noEndingDateFlag" : true,
            "cancelledFlag" : false,
            "dateCancelled" : null,
            "reasonCancelled" : "",
            "slaId" : null,
            "workOrder" : "",
            "internalNotes" : "",
            "applicationUnits" : null,
            "applicationLimit" : "0",
            "applicationCycle" : null,
            "applicationUnlimitedFlag" : false,
            "oneTimeFlag" : false,
            "coverAgreementTime" : false,
            "coverAgreementProduct" : false,
            "coverAgreementExpense" : false,
            "expiredDays" : "0",
            "billCycleId" : "2",
            "billOneTimeFlag" : false,
            "billTermsId" : 12,
            "billAmount" : "0",
            "periodType" : null,
            "_id" : ObjectId("57c7bd9051666ac615bc8404"),
            "_info" : {
                "lastUpdated" : ISODate("2016-06-01T16:17:45.000Z"),
                "updatedBy" : "Ali            "
            },
            "contact" : {
                "id" : "810",
                "name" : "Jarrod Rogers"
            },
            "agreementType" : {
                "id" : "32",
                "name" : "Agreement Template"
            }
        }
    ],
    "companySite" : [ 
        {
            "id" : 1125,
            "name" : "Main",
            "addressLine1" : "5425 W. Spring Creek Pkwy #270",
            "addressLine2" : null,
            "city" : "Plano",
            "state" : "TX",
            "zip" : "75024",
            "faxNumber" : null,
            "taxCodeId" : null,
            "expenseReimbursement" : null,
            "primaryAddressFlag" : true,
            "defaultShippingFlag" : false,
            "defaultBillingFlag" : true,
            "defaultMailingFlag" : false,
            "_id" : ObjectId("57c7beb951666ac615bc84e5"),
            "country" : {
                "id" : 1,
                "name" : "United States",
                "_info" : null
            },
            "_info" : {
                "lastUpdated" : ISODate("2016-09-01T05:12:28.000Z"),
                "updatedBy" : "LabTechInt"
            }
        }
    ],
    "status" : {
        "id" : "1",
        "name" : "Active"
    },
    "country" : {
        "id" : 1,
        "name" : "United States",
        "_info" : null
    },
    "id" : "19390",
    "__v" : 0
}

我想统计文档中的协议数量和联系人数量,并将数据按公司名称和 orgId 分组。

这是我想要的输出:

{
  "Company":        "Multi-Metal Manufacturing",
  "Organization":   "1",
  "AgreementCount" : 1,
  "ContactCount" :   4
}

我尝试了这个解决方案,但结果不如预期;它给了我所有字段的一般计数,但我想要一个具体的计数:

return Company.aggregate(
  {"$unwind":"$agreement"},
  {"$unwind":"$contact"},
  {"$unwind":"$companySite"},
  { $group: {
    _id: {
      "Organization": "$orgId",
      "Company": "$name"
    },
    "count": { $sum: 1 } } },
  {"$project": {
    "_id": 0,
    "Company": "$_id.Company",
    "Organization":"$_id.Organization",
    "Count": "$count"
  }
})

【问题讨论】:

    标签: node.js mongodb performance mongoose aggregation-framework


    【解决方案1】:

    假设 Companyname/orgId 是唯一的,您可以使用 $size 来获取您的数组的大小,从而使这变得非常简单:

    [
        {
            $project:{
                _id:false,
                Company: "$name",
                Organization: "$orgId",
                AgreementCount: {
                    $size: {$ifNull: ["$agreement",[]]}
                },
                ContactCount: {
                    $size: {$ifNull: ["$contact",[]]}
                }
            }
        }
    ]
    

    如果 Companyname/orgId 不是唯一的,那么您可以引入一个$group 阶段来汇总$size 产生的计数:

    [
        {
            $project:{
                _id:false,
                Company: "$name",
                Organization: "$orgId",
                AgreementCount: {
                    $size: {$ifNull: ["$agreement",[]]}
                },
                ContactCount: {
                    $size: {$ifNull: ["$contact",[]]}
                }
            }
        },
        {
            $group: {
                _id:{
                    Company: "$Company",
                    Organization: "$Organization"
                },
                AgreementCount: {$sum:"$AgreementCount"},
                ContactCount: {$sum:"$ContactCount"}
            }
        },
        {
            $project:{
                _id: false,
                Company: "$_id.Company",
                Organization: "$_id.Organization",
                AgreementCount: true,
                ContactCount: true
            }
        }
    ]
    

    【讨论】:

    • 您好,您使用唯一粘贴的查询没有按预期工作,它为所有人提供零,您粘贴的查询不是唯一的,不按公司分组
    • 我得到了这个解决方案 db.company.aggregate({$unwind:"$contact"},{$unwind:"$agreement"},{$group:{_id:{"company": "$name","organization":"$orgId"},"Contact":{$addToSet:"$contact._id"},"Agreement":{$addToSet:"$agreement._id"}}}, { "$project":{_id:0,"Company":"$_id.company","Organization":"$_id.organization","AgreementCount":{$size:"$Agreement"},"ContactCount": {$size:"$Contact"}}}).pretty();
    • 此解决方案适用于您在问题中提供的数据集。您是否正在使用您所指出的数据集以外的数据集?例如,您引用了路径“$contact._id”,但在您提供的示例数据中没有这样的路径。联系人数组元素仅包含属性名称。示例 {“名称”:“服务”}。除此之外,接受的答案和您评论中的解决方案的主要问题是它效率低下。您不必要地展开两个数组,创建本质上重复的数据,然后使用 $addToSet 删除重复。
    • 我只想计算整个公司集合中的联系人数量和协议数量然后我想按公司名称和 orgId 的计数进行分组。我是 mongo 的新手,如果您认为有更好的解决方案,请告诉我。我正在更新示例文档。
    • 我为数据集道歉,实际上它太大了,所以我没有早点发布
    【解决方案2】:
    db.company.aggregate(
      {$unwind:"$contact"},
      {$unwind:"$agreement"},
      {$group:
        {_id: {"company":"$name","organization":"$orgId"},
         "Contact":{$addToSet:"$contact._id"},
         "Agreement":{$addToSet:"$agreement._id"}
        }
      },
      {"$project":
        {_id:0,
         "Company":"$_id.company",
         "Organization":"$_id.organization",
         "AgreementCount":{$size:"$Agreement"},
         "ContactCount":{$size:"$Contact"}
        }
      }).pretty();
    

    【讨论】:

      【解决方案3】:
      return Company.aggregate([{
          $project: {
              ITBCompanyId: 1,
              name: 1,
              contact: {
                  $size: "$contact"
              },
              agreement: {
                  $size: "$agreement"
              },
              whoIs: {
                  $size: "$whois"
              },
              companySite: {
                  $size: "$companySite"
              }
          }
      }])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-26
        • 2020-10-18
        • 2013-01-20
        • 2020-04-26
        • 2017-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多