简体   繁体   中英

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.
link: http://docs.mongodb.org/manual/reference/operator/update/sort/

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM