如何解决MongoDB聚合,$ addFields在$ cond上不起作用
我一直在使用调查收集和$ lookup查找调查问题的相关答案。
现在,我想使用$ addField引入一个user_oid并创建一个“ user_answer_count”。
代码:
Survey.aggregate([
{ $match: { team_oid: mongoose.Types.ObjectId(req.params.t_oid) } },{ $addFields: { count_questions: { $size: "$questions"} } },{ $unwind: { path: "$questions" } },{ $lookup: { from: 'answers',localField: 'questions',foreignField: 'question_oid',as: 'answer' } },{ $unwind: { path: "$answer",preserveNullAndEmptyArrays: true } },{ $addFields: {
answer_count: { $cond: [{ $eq: [{ $type: "$answer" },"object" ]},1,0] } },user_answer_count: { $cond: [{ $eq: ["$answer.user_oid",mongoose.Types.ObjectId(req.params.u_oid) ]},0] }
},{ $lookup: { from: 'votes',localField: '_id',foreignField: 'surveyOid',as: 'votes' } },{ $unwind: { path: "$votes",{ $addFields: { vote_count: { $cond: [{ $eq: [{ $type: "$votes" },"object"] },0.2,0] } } },{
$group: {
_id: "$_id",huddle_number: { $first: "$huddle_number" },count_questions: { $first: "$count_questions" },count_answers: { $sum: "$answer_count" },count_votes: { $sum: "$vote_count" },count_user_answers: { $sum: "$user_answer_count" },sefirot_state: { $first: "$sefirot_state" },created_date: { $first: "$created_date" },avg_positive: { $avg: "$answer.positive" },avg_creative: { $avg: "$answer.creative" },avg_focused: { $avg: "$answer.focused" },avg_friendly: { $avg: "$answer.friendly" },avg_aligned: { $avg: "$answer.aligned" },avg_alert: { $avg: "$answer.alert" }
}
}
]).exec((err,doc) => {
这里的所有内容都可以使用,第一个$ addField“ answer_count”可以完美使用。但是第二个问题“ user_answer_count”却使整个过程失败。
控制台说: Arguments must be aggregate pipeline operators
这是我第一次尝试将$ lookup与$ addFields一起使用,因此建议表示赞赏!
编辑:
示例文档
**Survey**
_id : 5f5a372d9ea9981e7c5773cb
questions :
0 : 5f522b025dd8993e58283522
1 : 5f47a892db023557105e2be3
2 : 5f522a9d5dd8993e58283520
3 : 5f0e23ef2e0fcb3fe04a7314
4 : 5f522b285dd8993e58283523
created_date : 2020-09-10T14:24:45.439+00:00
team_oid : 5f44cc20c74f8a444851d9c2
huddle_number : 22
sefirot_state : "Aligned"
__v : 0
**Answer**
_id : 5f58bb04772a5943a0b54ec9
question : "What does "winning" look like in this team?"
question_oid : 5f522bc55dd8993e58283526
user_team_oid : 5f44cc20c74f8a444851d9c2
user_oid : 5f1ef3e8accff82f3cae3957
comment : "It means Cobra Kai Never Die and Only Get Better"
created_date : 2020-09-09T11:22:44.098+00:00
__v : 0
解决方法
几乎没有修复程序,缺少括号和$cond
语法不正确,这也是获取数组计数的错误方式。
- 用于
$size
的数组中使用answer_count
的元素数 - 您可以使用
$reduce
数组运算符来获取用户的计数,而无需使用$unwind
答案数组
{ $lookup: { ... } },// skipping
{
$addFields: {
answer_count: { $size: "$answer" },user_answer_count: {
$reduce: {
input: "$answer",initialValue: 0,in: {
$cond: [
{ $eq: ["$$this.user_oid",mongoose.Types.ObjectId(req.params.u_oid)] },{ $add: ["$$value",1] },"$$value"
]
}
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。