簡體   English   中英

MongoDB,Java,按第一個數組條目排序

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

我正在嘗試通過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文檔卻沒有提到它。 使用$符號匹配第一個項目,但指定數組元素編號似乎有效。 如果有人有更好的文檔描述行為,請回復鏈接。

從文檔中

更新陣列中的文檔

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


文檔在這里

實際上,您無法通過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收集了一些active ,然后排序的第一天升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)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM