我正在使用mongodb为我当前的项目收集如下
{
"_id" : ObjectId("5a3a567a8fb6e20f67cb10f7"),
"player_id" : "5a26453db767c01262eddc4e",
"quiz_type" : "Single",
"created_date" : ISODate("2017-12-20T12:24:26Z"),
"questions_answered" : [
{
"question_id" : ObjectId("5a3a0bfc2d53f131068b4567"),
"player_selection_status" : "Wrong",
"time_taken" : 10,
"points_gained" : 0,
"like" : 1,
"answered_date" : "2017-12-20T17:54:30+05:30"
},
{
"question_id" : ObjectId("5a3a0bfc2d53f131068b4568"),
"player_selection_status" : "Correct",
"time_taken" : 10,
"points_gained" : 5,
"like" : 1,
"answered_date" : "2017-12-20T17:54:32+05:30"
},
{
"question_id" : ObjectId("5a3a0bfc2d53f131068b4569"),
"player_selection_status" : "Correct",
"time_taken" : 10,
"points_gained" : 5,
"like" : 1,
"answered_date" : "2017-12-20T17:54:34+05:30"
},
{
"question_id" : ObjectId("5a3a0bfc2d53f131068b456a"),
"player_selection_status" : "Wrong",
"time_taken" : 10,
"points_gained" : 0,
"like" : 1,
"answered_date" : "2017-12-20T17:54:35+05:30"
},
{
"question_id" : ObjectId("5a3a0bfc2d53f131068b456c"),
"player_selection_status" : "Correct",
"time_taken" : 10,
"points_gained" : 5,
"like" : 1,
"answered_date" : "2017-12-20T17:54:37+05:30"
}
],
"__v" : 0
}
我需要获取points_gained的数据:仅限5,我的查询是
db.player_quiz.find({player_id: "5a26453db767c01262eddc4e", 'questions_answered.points_gained': 5}).pretty()
使用上述查询我得到了所有结果..我只需要记录有questions_answered.points_gained:仅限5个
请帮我解决。
答案 0 :(得分:1)
db.player_quiz.aggregate(
// Pipeline
[
// Stage 1
{
$unwind: {
"path": '$questions_answered'
}
},
// Stage 2
{
$match: {
'questions_answered.points_gained': 5
}
},
// Stage 3
{
$group: {
_id: '$_id',
questions_answered: {
$addToSet: '$questions_answered'
},
doc: {
$first: '$$ROOT'
}
}
},
// Stage 4
{
$project: {
questions_answered: 1,
"player_id": '$doc.player_id',
'quiz_type': '$doc.quiz_type',
'created_date': '$doc.created_date'
}
},
]
);