2014-07-23 29 views
1

我試圖通過Java API在我的MongoDB上執行查找後對值進行排序。結果列表包含以下項目:MongoDB,Java,通過第一個數組條目進行排序

{ 
"_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); 

光標值不受此代碼排序。你可以幫我嗎?

+1

這可能是一個更容易解決這在Java代碼比MongoDB的層上。這對你來說是否合適,還是你堅持要對數據庫進行排序? – Philipp

+0

在java中排序是好的,除非你需要查詢大量的文件 – injecteer

+1

你試過BasicDBObject orderBy = new BasicDBObject(「labels.0.value」,1); – Mike

回答

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

這些是單獨申報的。

+0

謝謝尼爾,puh ...複雜;)感謝Philipp,我會嘗試對Java代碼中的元素進行排序。 –

5

你試過

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

這不是很明顯,但MongoDB的文檔逃避它。使用$符號匹配第一個項目,但指定數組元素編號似乎工作。如果任何人有更好的描述行爲的文件,請回復鏈接。在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 } }) 


文檔是here

相關問題