MongoDB新手在这里...
当我在shell中执行db.students.find().pretty()时,我会从我的collection...like中得到一个很长的列表,所以..
{
"_id" : 19,
"name" : "Gisela Levin",
"scores" : [
{
"type" : "exam",
"score" : 44.51211101958831
},
{
"type" : "quiz",
"score" : 0.6578497966368002
},
{
"type" : "homework",
"score" : 93.36341655949683
},
{
"type" : "homework",
"score" : 49.43132782777443
}
]
}现在我已经有了大约100多个这样的…我需要在每个上面运行下面的代码…
lowest_hw_score =
db.students.aggregate(
// Initial document match (uses index, if a suitable one is available)
{ $match: {
_id : 0
}},
// Expand the scores array into a stream of documents
{ $unwind: '$scores' },
// Filter to 'homework' scores
{ $match: {
'scores.type': 'homework'
}},
// Sort in descending order
{ $sort: {
'scores.score': 1
}},
{ $limit: 1}
)因此,我可以在每个结果上运行如下内容
for item in lowest_hw_score:
print lowest_hw_score现在,"lowest_score“只在一个项目上有效,我要在collection...how中的所有项目上运行它,我要这样做吗?
发布于 2012-11-20 09:28:33
> db.students.aggregate(
{ $match : { 'scores.type': 'homework' } },
{ $unwind: "$scores" },
{ $match:{"scores.type":"homework"} },
{ $group: {
_id : "$_id",
maxScore : { $max : "$scores.score"},
minScore: { $min:"$scores.score"}
}
});您实际上并不需要第一个$match,但是如果"scores.type“被编入索引,这意味着它将在解开分数之前被使用。(我不相信在$unwind之后,mongo将能够使用索引。)
结果:
{
"result" : [
{
"_id" : 19,
"maxScore" : 93.36341655949683,
"minScore" : 49.43132782777443
}
],
"ok" : 1
}编辑:在mongo shell中测试和更新
https://stackoverflow.com/questions/13465062
复制相似问题