在mongodb中以嵌套文档的forms检索数据

以下是我在MongoDB收集中的一组样本数据。

{year : 2010 , studentName: "John", grades :{science: 70, maths: 80, english: 85 }} {year : 2010 , studentName: "Denver", grades :{science: 75, maths: 85, english: 85 }} {year : 2010 , studentName: "Harry", grades :{science: 85, maths: 75, english: 65 }} {year : 2011 , studentName: "John", grades :{science: 70, maths: 80, english: 85 }} {year : 2011 , studentName: "Denver", grades :{science: 75, maths: 85, english: 85 }} {year : 2011 , studentName: "Harry", grades :{science: 85, maths: 75, english: 65 }} 

我想用下面的模式检索嵌套文档的数据。

 [{ "year": 2010, "studentGrades": [ { "studentName": "John", "grades": { "science": 70, "maths": 80, "english": 85 } }, { "studentName": "Denver", "grades": { "science": 75, "maths": 85, "english": 85 } } ] }, { "year": 2011, "studentGrades": [ { "studentName": "John", "grades": { "science": 70, "maths": 80, "english": 85 } }, { "studentName": "Denver", "grades": { "science": 75, "maths": 85, "english": 85 } } ] } ] 

你能不能帮我写一个mongodb查询命令来获取date范围,例如2009 -2011与以上格式的结果?

使用具有三个运算符的pipe道的聚合框架。 第一个$match步骤作为一个filter,只允许文档进入满足给定条件的stream水线。 这个操作符与find()方法类似,因为它使用标准的MongoDB查询。 对于每个input文档,输出一个文档(匹配)或零个文档(不匹配)。 这是指定查询在date范围内查找数据的位置。 例如2009 -2011含)。 在这种情况下,您可以使用带$lte操作符的$gte来创build范围查询(对于包含范围),对$gt操作符用$lt来创build独占范围查询。

第二个$group步骤将按year字段对集合中的文档进行分组,此键变为您的组_idstudentGrades数组然后由$push操作符填充,该操作符接收文档expression式。

最后的$projectpipe道通过用year字段replace_id jey来重新塑造文档的字段,而另一个字段保持不变。

因此,您正在寻找以下聚合操作:

 db.students.aggregate([ { "$match": { "year": { "$gte": 2009, "$lte": 2011 } } }, { "$group": { "_id": "$year", "studentGrades": { "$push": { "studentName": "$studentName", "grades": "$grades" } } } }, { "$project": { "_id": 0, "year": "$_id", "studentGrades": 1 } } ])