MongoDB,Java,按第一个数组条目排序

时间:2014-07-23 13:34:40

标签: java mongodb aggregation-framework

我试图通过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);

此代码未对游标值进行排序。你能救我吗?

4 个答案:

答案 0 :(得分:6)

你试过吗

BasicDBObject orderBy = new BasicDBObject("labels.0.value", 1);

这并不明显,但是MongoDB文档却没有提到它。使用$符号匹配第一个项目,但指定数组元素编号似乎有效。如果有人有更好的文档描述行为,请回复链接。

来自文档

  

更新数组中的文档

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( { <query selector> }, { <update operator>: { "array.$.field" : value } } )


文档为here

答案 1 :(得分:1)

您实际上无法通过MongoDB中文档中特定的数组索引进行“排序”。 CT 如果你真的必须这样做,那么你需要aggregation framework来“提取”要排序的元素。

我知道列表表单实际上已弃用,因此此代码仅用于演示。将您的管道实际定义为单个变量,并将它们作为参数提供给聚合:

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

单独声明的地方。

答案 2 :(得分:1)

我在寻找如何按数组的第一项对MongoDB(在流星中)排序时发现了这个问题/答案

我用它来查找Schedules集合中所有active的文档,然后在days数组的第一天之前按升序排序。

Schedules.find(
  {
    active: true,
  },
  {
    sort: { 'days.0': 1 },
  },
)

示例Schedule的集合文档中包含周一,周三,周五的时间表,如下所示:

{
  _id: 9dh3ld0d7d0d,
  userId: UJD9dKd8edo,
  active: true,
  days: [1, 3, 5],
}

答案 3 :(得分:0)

自MongoDB 3.0 Java Api以来,您可以使用com.mongodb.client.model.Sorts

例如:

col.find().sort(Sorts.orderBy(Sorts.descending(fieldname)));
相关问题