简体   繁体   English

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

[英]MongoDB, Java, sort by first array entry

I'm trying to sort values after executing a find on my MongoDB by Java API. 我正在尝试通过Java API在MongoDB上执行查找后对值进行排序。 The result list contains the following entries: 结果列表包含以下条目:

{
"_id": "P17-223",
"property": "P17",
"itemid": 223,
"labels": [
  {
    "language": "en",
    "value": "Greenland"
  },
  {
    "language": "es",
    "value": "Groenlandia"
  },
  {
    "language": "de",
    "value": "Grönland"
  }
]

} }

I want to sort by the first entry of the array labels : 我想按数组标签的第一个条目排序:

  DBCursor cursor = getCollection().find(query);
  BasicDBObject orderBy = new BasicDBObject("labels[0].value", 1);
  cursor.sort(orderBy);

Cursor values are not sorted by this code. 此代码不对游标值进行排序。 Can you help me? 你能帮助我吗?

Have you tried 你有没有尝试过

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

It's not obvious, but the MongoDB documentation eludes to it. 这并不明显,但是MongoDB文档却没有提到它。 Using the $ sign matches the first item, but specifying the array element number seems to work. 使用$符号匹配第一个项目,但指定数组元素编号似乎有效。 If anyone has a better document describing the behavior, please reply with the link. 如果有人有更好的文档描述行为,请回复链接。

From the documentation 从文档中

Update Documents in an Array 更新阵列中的文档

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


Documentation is here 文档在这里

You cannot actually "sort" by a specific index of an array within a document in MongoDB. 实际上,您无法通过MongoDB中文档中特定的数组索引进行“排序”。 ct If you really must do this then you need the aggregation framework to "extract" the element to sort on. ct如果你真的必须这样做,那么你需要聚合框架来“提取”要排序的元素。

I know the list form is actually deprecated, so this code is just for demonstration. 我知道列表表单实际上已弃用,因此此代码仅用于演示。 Acutally define your pipeline as individual variables and feed those as argument to aggregate: 将您的管道实际定义为单个变量,并将它们作为参数提供给聚合:

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

That gives you the serialized version which is the JSON form of: 这为您提供了序列化版本,它是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} }
])

Better applied in your code as: 更好地应用于您的代码:

collection.aggregate(unwind,group,sort);

Where those are individually declared. 那些是单独宣布的。

I found this question/answer when looking for How to sort MongoDB (in Meteor) by first item of array 我在寻找如何通过第一项数组对MongoDB(在Meteor中)进行排序时找到了这个问题/答案...

I used this to find all documents in the Schedules collection which are active and then sort ascending by the first day in the days array. 我用这个来查找所有文件Schedules收集了一些active ,然后排序的第一天升days阵。

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

A sample Schedule collection document with a Monday, Wednesday, Friday schedule looks something like this: 带有星期一,星期三,星期五计划的示例Schedule集合文档如下所示:

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

Since MongoDB 3.0 Java Api, you can use com.mongodb.client.model.Sorts 从MongoDB 3.0 Java Api开始,您可以使用com.mongodb.client.model.Sorts

Exemple use : 例如:

col.find().sort(Sorts.orderBy(Sorts.descending(fieldname)));

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

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