MongoDB,Java,按第一个数组条目排序
我正在尝试通过Java API在MongoDB上执行查找后对值进行排序。 结果列表包含以下条目:
{ "_id": "P17-223", "property": "P17", "itemid": 223, "labels": [ { "language": "en", "value": "Greenland" }, { "language": "es", "value": "Groenlandia" }, { "language": "de", "value": "Grönland" } ]
}
我想按数组标签的第一个条目排序:
DBCursor cursor = getCollection().find(query); BasicDBObject orderBy = new BasicDBObject("labels[0].value", 1); cursor.sort(orderBy);
此代码不对游标值进行排序。 你能帮助我吗?
你有没有尝试过
BasicDBObject orderBy = new BasicDBObject("labels.0.value", 1);
这并不明显,但是MongoDB文档却没有提到它。 使用$符号匹配第一个项目,但指定数组元素编号似乎有效。 如果有人有更好的文档描述行为,请回复链接。
从文档中
更新arrays中的文档
The positional $ operator facilitates updates to arrays that contain embedded documents. Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator. db.collection.update( { }, { : { "array.$.field" : value } } )
文档在这里
实际上,您无法通过MongoDB中文档中特定的数组索引进行“排序”。 ct如果你真的必须这样做,那么你需要聚合框架来“提取”要排序的元素。
我知道列表表单实际上已弃用,因此此代码仅用于演示。 将您的管道实际定义为单个变量,并将它们作为参数提供给聚合:
BasicDBList pipeline = new BasicDBList(); list.add(new BasicDBObject("$unwind","$labels")); list.add(new BasicDBObject("$group", new BasicDBObject("_id","$_id") .append("property", new BasicDBObject("$first","$property")) .append("itemid", new BasicDBObject("$first","$itemid")) .append("labels", new BasicDBObject("$push","$labels")) .append("maxLabel", new BasicDBObject("$max", "$labels.value")) )); list.add(new BasicDBObject("$sort", new BasicDBObject("maxLabel",1))); System.out.println(pipeline);
这为您提供了JSON格式的序列化版本:
db.collection.aggregate([ { "$unwind" : "$labels" }, { "$group": { "_id": "$_id", "property": { "$first" : "$property" }, "itemid": { "$first" : "$itemid" }, "labels": { "$push" : "$labels" }, "maxLabel": { "$max" : "$labels.value"} }}, { "$sort" : { "maxLabel" : 1} } ])
更好地应用于您的代码:
collection.aggregate(unwind,group,sort);
那些是单独宣布的。
我在寻找如何通过第一项数组对MongoDB(在Meteor中)进行排序时发现了这个问题/答案…
我使用它来查找Schedules
集合中所有活动的文档,然后在days
数组的第一天按升序排序。
Schedules.find( { active: true, }, { sort: { 'days.0': 1 }, }, )
带有星期一,星期三,星期五计划的示例Schedule
集合文档如下所示:
{ _id: 9dh3ld0d7d0d, userId: UJD9dKd8edo, active: true, days: [1, 3, 5], }
从MongoDB 3.0 Java Api开始,您可以使用com.mongodb.client.model.Sorts
例如:
col.find().sort(Sorts.orderBy(Sorts.descending(fieldname)));