user3003675 user3003675 - 1 year ago 153
Java Question

Sort array of subdocuments in mongodb with java

uI have an array of subdocument in the document of mongodb.

I want to sort those subdocuments.
I found it is possible to sort while updating the array.


I want to do this in java.
Here's part of my code:

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);

But it turns out that it didn't turn "operations" to operators but directly push them into documents and made "$each", "$slice" and "$sort" as fields.
Where did I do wrong?

Answer Source

I have implemented the java version of the query shown in the link you mentioned above.

Query is :

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

Using Java Driver you can implement it as follows :

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();

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)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download