2017-10-09 63 views
2

我有一個集合,其中文檔都是這樣

{ 
    "_id" : "api", 
    "titleAndTimeDetails" : [ 
     { 
      "Title" : "api data", 
      "timeTaken" : NumberLong(8091446063) 
     }, 
     { 
      "Title" : "class data", 
      "timeTaken" : NumberLong(519163710) 
     }, 
     { 
      "Title" : "API or datasets for age world", 
      "timeTaken" : NumberLong(34245103) 
     }, 
     { 
      "Title" : "What does a null result mean API?", 
      "timeTaken" : NumberLong(171605137) 
     } 
] 
} 

/* 2 */ 
{ 
    "_id" : "government", 
    "titleAndTimeDetails" : [ 
     { 
      "Title" : "Is there an open standard for the CAFR (Comprehensive Annual Finance Report)?", 
      "timeTaken" : NumberLong(574587563) 
     }, 
     { 
      "Title" : "College Scorecard full data base", 
      "timeTaken" : NumberLong(9422714) 
     }, 
     { 
      "Title" : "List of German local politicians", 
      "timeTaken" : NumberLong(691311396) 
     }, 
     { 
      "Title" : "Trying to extrapolate patient costs by physician from public Medicare pricing data", 
      "timeTaken" : NumberLong(9590779130) 
     }, 
     { 
      "Title" : "Are there good examples of open read-write APIs in Federal government?", 
      "timeTaken" : NumberLong(1784634763) 
     } 
    ] 
} 

查詢語句是顯示Title爲此採取了最短時間每個「_id」。請有人可以幫助我嗎?

回答

2

你應該先$unwindtitleAndTimeDetails然後通過titleAndTimeDetails.timeTaken$sort最後由_id$group並獲得$第一的Title

db.collection.aggregate([ 
    { $unwind: "$titleAndTimeDetails" }, 
    { $sort: { "titleAndTimeDetails.timeTaken": 1 } }, 
    { $group: { _id: "$_id", title: { $first: "$titleAndTimeDetails.Title" } } } 
]) 
+0

$ unwind對於這種情況是一個代價高昂的操作,我們可以在聚合管道中使用$ project和$ min來獲得所需的結果。請看我的答案。 –

+0

@ClementAmarnath,我更喜歡你的查詢。但是如果你沒有直接投射多重文件(我們不這樣做),展開費用並不高。無論是我的還是你的查詢,昂貴的部分都是'sort'($ min也使用排序)。所以它可以忽略不計。你的查詢有更好的可讀性,雖然 – barbakini

1
db.collection.aggregate([{$project: { timeTaken:{$min:"$titleAndTimeDetails. 
timeTaken"}}}]) 

是如下圖所示

{ "_id" : "api", "timeTaken" : NumberLong(34245103) } 
{ "_id" : "government", "timeTaken" : NumberLong(9422714) } 

,我們得到了在這個問題給出的樣本文件的結果,要獲得期望的結果$project和聚合管道$min使用

+0

非常感謝:)它的工作。查詢現在正在執行正常。我錯過了這種排序功能 –