我在检索mongo数据时有以下C#代码:
var match = new BsonDocument
{
{ "$match",
new BsonDocument { { "Country", paramsEntity.Country },
{ "Staff_ID", String.IsNullOrEmpty(paramsEntity.StaffID) ? "$Staff_ID" : paramsEntity.StaffID },
{ "WeCare.CustSatisfaction.Trans_Year.$", paramsEntity.Year == null ? "$WeCare.CustSatisfaction.Trans_Year.$" : paramsEntity.Year.ToString() },
{ "WeCare.CustSatisfaction.Trans_Month.$", paramsEntity.Month == null ? "$WeCare.CustSatisfaction.Trans_Month.$" : paramsEntity.Month.ToString() },
}
}
};
var unwind = new BsonDocument("$unwind", "$WeCare.CustSatisfaction");
var group = new BsonDocument
{
{ "$group",
new BsonDocument
{
{ "_id", new BsonDocument { { "Country","$Country" },
{ "Staff_ID", "$Staff_ID" },
{ "Trans_Year", "$WeCare.CustSatisfaction.Trans_Year" },
{ "Trans_Month", "$WeCare.CustSatisfaction.Trans_Month" }
}
},
{ "$push",
new BsonDocument
{
{ "CustPastAnswers", new BsonDocument { { "SurveyComment", "$WeCare.CustPastAnswers.SurveyComment" } } }
}
},
{ "HH", new BsonDocument { { "$sum", "$WeCare.CustSatisfaction.HH" } } } }
}
};
var project = new BsonDocument
{
{
"$project",
new BsonDocument
{
{"_id", 0},
{"Staff_ID", "$_id.Staff_ID"},
{ "CustSatisfaction", new BsonDocument { { "Trans_Year", "$_id.Trans_Year" },
{ "Trans_Month", "$_id.Trans_Month" },
{ "HH", 1 },
} },
{ "CustPastAnswers", new BsonDocument { { "SurveyComment", "$SurveyComment" } } },
}
}
};
var pipeline = new[] { match, unwind, group, project };
var result = mongoDB.Consultant.Aggregate<BsonDocument>(pipeline).ToList();
var b = result.Select(c => BsonSerializer.Deserialize<MongoConsultantResult>(c)).ToList();
我在$ push那里遇到错误。实际上我正在尝试为没有任何分组的员工检索所有CustPastAnswers。有没有更好的方法呢?
以下我的mongo查询,它运行正常:
db.getCollection('Consultant').aggregate([
{$unwind: "$WeCare.CustSatisfaction"} // important step!
,{$group: {_id: {Country: "$Country",
Staff_ID: "$Staff_ID",
Trans_Year: "$WeCare.CustSatisfaction.Trans_Year",
Trans_Month: "$WeCare.CustSatisfaction.Trans_Month"},
CustPastAnswers:{$push: {
SurveyComment:"$WeCare.CustPastAnswers.SurveyComment"
}},
HH: {$sum: "$WeCare.CustSatisfaction.HH"}}}
]);
答案 0 :(得分:0)
根据您的mongo查询,&#34; group&#34;部分代码应该是这样的。
var group = new BsonDocument
{
{ "$group",
new BsonDocument
{
{ "_id", new BsonDocument { { "Country","$Country" },
{ "Staff_ID", "$Staff_ID" },
{ "Trans_Year", "$WeCare.CustSatisfaction.Trans_Year" },
{ "Trans_Month", "$WeCare.CustSatisfaction.Trans_Month" }
}
},
{ "CustPastAnswers", new BsonDocument { { "$push",
new BsonDocument { { "SurveyComment", "$WeCare.CustPastAnswers.SurveyComment" } }
}
}
},
{ "HH", new BsonDocument { { "$sum", "$WeCare.CustSatisfaction.HH" } }
}
}
}
};