如何在mongoDB中对集合记录中的数组进行排序MongoDB noob在这里......好的,我有一个学生集合,每个都有一个如下所示的记录....我想按照降序排序'类型':'家庭作业'分数。那个咒语在mongo shell上是什么样的?> db.students.find({'_id': 1}).pretty(){
"_id" : 1,
"name" : "Aurelia Menendez",
"scores" : [
{
"type" : "exam",
"score" : 60.06045071030959
},
{
"type" : "quiz",
"score" : 52.79790691903873
},
{
"type" : "homework",
"score" : 71.76133439165544
},
{
"type" : "homework",
"score" : 34.85718117893772
}
]}我正在尝试这个咒语.... doc = db.students.find()
for (_id,score) in doc.scores:
print _id,score但它不起作用。
3 回答

温温酱
TA贡献1752条经验 获得超4个赞
您需要在应用程序代码中操作嵌入式数组,或在MongoDB 2.2中使用新的聚合框架。
mongo
shell中的示例聚合:
db.students.aggregate( // Initial document match (uses index, if a suitable one is available) { $match: { _id : 1 }}, // 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 }})
样本输出:
{ "result" : [ { "_id" : 1, "name" : "Aurelia Menendez", "scores" : { "type" : "homework", "score" : 71.76133439165544 } }, { "_id" : 1, "name" : "Aurelia Menendez", "scores" : { "type" : "homework", "score" : 34.85718117893772 } } ], "ok" : 1}

长风秋雁
TA贡献1757条经验 获得超7个赞
这就是我们用JS和mongo控制台解决这个问题的方法:
db.students.find({"scores.type": "homework"}).forEach( function(s){ var sortedScores = s.scores.sort( function(a, b){ return a.score<b.score && a.type=="homework"; } ); var lowestHomeworkScore = sortedScores[sortedScores.length-1].score; db.students.update({_id: s._id},{$pull: {scores: {score: lowestHomeworkScore}}}, {multi: true}); })

噜噜哒
TA贡献1784条经验 获得超7个赞
这是java代码,可用于找出数组中的最低分数并将其删除。
public class sortArrayInsideDocument{public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB db = client.getDB("school"); DBCollection lines = db.getCollection("students"); DBCursor cursor = lines.find(); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); BasicDBList dbObjectList = (BasicDBList) cur.get("scores"); Double lowestScore = new Double(0); BasicDBObject dbObject = null; for (Object doc : dbObjectList) { BasicDBObject basicDBObject = (BasicDBObject) doc; if (basicDBObject.get("type").equals("homework")) { Double latestScore = (Double) basicDBObject .get("score"); if (lowestScore.compareTo(Double.valueOf(0)) == 0) { lowestScore = latestScore; dbObject = basicDBObject; } else if (lowestScore.compareTo(latestScore) > 0) { lowestScore = latestScore; dbObject = basicDBObject; } } } // remove the lowest score here. System.out.println("object to be removed : " + dbObject + ":" + dbObjectList.remove(dbObject)); // update the collection lines.update(new BasicDBObject("_id", cur.get("_id")), cur, true, false); } } finally { cursor.close(); }}}
添加回答
举报
0/150
提交
取消