2017-10-09 10 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) 
     } 
    ] 
} 

ようにされたコレクションを持っているクエリステートメントは、撮影した最小時間を持っているそれぞれの「_id」のためTitleを表示することです。誰かがこれで私を助けることができますか?

答えて

2

最初$unwindtitleAndTimeDetailstitleAndTimeDetails.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"}}}]) 

は、私たちが問題に与えられたサンプル文書の取得結果は、$projectおよびアグリゲーションパイプラインの$min

を使用している目的の結果を得るには

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

の下に示されているよう

+0

ありがとうございます:)それは働いた。クエリは現在正常に実行されています。私はこのソート機能が欠けていた –

関連する問題