简体   繁体   English

使用Java对mongodb中的子文档数组进行排序

[英]Sort array of subdocuments in mongodb with java

uI have an array of subdocument in the document of mongodb. 我在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/ 链接: http//docs.mongodb.org/manual/reference/operator/update/sort/

I want to do this in java. 我想在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. 但是事实证明,它并没有将“操作”交给操作员,而是直接将其推入文档并将“ $ each”,“ $ slice”和“ $ sort”作为字段。 Where did I do wrong? 我在哪里做错了?

I have implemented the java version of the query shown in the link you mentioned above. 我已经实现了您上面提到的链接中显示的查询的Java版本。

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 : 使用Java驱动程序,可以实现以下步骤:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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