u在mongodb的文档中有一个子文档数组 我想对那些子文档进行排序。 我发现在更新阵列时可以进行排序 链接:http://docs.mongodb.org/manual/reference/operator/update/sort/
我想在java中这样做。
这是我的代码的一部分:
BasicDBObject each = new BasicDBObject("$each", input);
BasicDBObject operations = each.append("$slice", "-10").append("$sort", new BasicDBObject("order",1));
push = new BasicDBObject("$push", new BasicDBObject("datas", operations));
collection.update(query, push);
但事实证明,它没有将“操作”转变为操作员,而是将它们直接推入文档中,并将“$ each”,“$ slice”和“$ sort”作为字段。 我哪里做错了?
答案 0 :(得分:4)
我已经实现了您在上面提到的link中显示的java版本的查询。
查询是:
db.students.update( { name: "joe" },
{ $push: { quizzes: { $each: [ { id: 3, score: 8 },
{ id: 4, score: 7 },
{ id: 5, score: 6 } ],
$sort: { score: 1 },
$slice: -5
}
}
}
)
使用Java Driver可以按如下方式实现:
DBCollection coll = db.getCollection("students");
DBObject query = new BasicDBObject("name", "joe");
DBObject dbObj1 = new BasicDBObject();
dbObj1.put("id", 3);
dbObj1.put("score", 8);
DBObject dbObj2 = new BasicDBObject();
dbObj2.put("id", 4);
dbObj2.put("score", 7);
DBObject dbObj3 = new BasicDBObject();
dbObj3.put("id", 5);
dbObj3.put("score", 6);
BasicDBList eachList = new BasicDBList();
eachList.add(dbObj1);
eachList.add(dbObj2);
eachList.add(dbObj3);
BasicDBObject quizzesObj = new BasicDBObject();
quizzesObj.put("$each", eachList);
quizzesObj.put("$sort", new BasicDBObject("score", 1));
quizzesObj.put("$slice", -5);
coll.update(query, new BasicDBObject("$push", new BasicDBObject("quizzes", quizzesObj)));