说,有两个这样的文件
{
"_id" : ObjectId("56554226da00060cd7dd7db5"),
"SegmentName" : "LTV90-Sub Prime",
"Segment_Behaviour" : "LTV90",
"Segment_Risk" : "Sub Prime",
"CohortMonthYear" : "01-01-2010",
"CohortQuarterYear" : "Q1 2010",
"DriverName" : "Active rate",
"MonthsOnBooks" : 2,
"DriverValue" : 0.9315880000000000,
"Accounts" : 5400,
"PortfolioId" : ObjectId("56554225c95a8a161c262853")
}
{
"_id" : ObjectId("56554226da00060cd7dd7db4"),
"SegmentName" : "LTV140-Near Prime",
"Segment_Behaviour" : "LTV140",
"Segment_Risk" : "Near Prime",
"CohortMonthYear" : "01-01-2010",
"CohortQuarterYear" : "Q1 2010",
"DriverName" : "Active rate",
"MonthsOnBooks" : 1,
"DriverValue" : 0.9800000000000000,
"Accounts" : 5400,
"PortfolioId" : ObjectId("56554225c95a8a161c262853")
}
当正则表达式“Segment_”匹配时,我需要进行聚合并提取所有字段名称和值。
目前我正在使用PortfolioId匹配文档,然后使用以下查询聚合SegmentName,Accounts。
db.PortfolioData.aggregate([{$match:{PortfolioId:ObjectId("56554225c95a8a161c262853")}},
{"$group": {
"_id": {"PortfolioId": "$PortfolioId", "SegmentName": "$SegmentName", "Accounts": "$Accounts"},}}]
);
现在,当正则表达式与“Segment _”匹配时,我还需要获取字段名称和值。
当前结果
{
"result" : [
{
"_id" : {
"PortfolioId" : ObjectId("56554225c95a8a161c262853"),
"SegmentName" : "LTV90-Sub Prime",
"Accounts" : 5400
}
},
{
"_id" : {
"PortfolioId" : ObjectId("56554225c95a8a161c262853"),
"SegmentName" : "LTV140-Near Prime",
"Accounts" : 24718
}
},
],
"ok" : 1.0000000000000000
}
预期结果:
{
"result": [
{
"_id": {
"PortfolioId": ObjectId("56554225c95a8a161c262853"),
"SegmentName": "LTV90-Sub Prime",
"Segment_Behaviour": "LTV90",
"Segment_Risk": "Sub Prime",
"Accounts": 7675
}
},
{
"_id": {
"PortfolioId": ObjectId("56554225c95a8a161c262853"),
"SegmentName": "LTV140-Near Prime",
"Segment_Behaviour": "LTV140",
"Segment_Risk": "Near Prime",
"Accounts": 24718
}
},
],
"ok": 1.0000000000000000
}
由于