2017-06-26 73 views
2

我必須根據查找結果對最終結果進行排序。下面是我的彙總查詢:

{ $match : {status:'active'}, 
{ $limit : 10}, 
{ $lookup: 
    { 
    from  : "metas", 
    localField : "_id", 
    foreignField: "post_id", 
    as   : "meta" 
    } 
} 

此查詢產生的結果爲:

{ 
    "_id": "594b6adc2a8c4f294025e46e", 
    "title": "Test 1", 
    "created_at": "2017-06-22T06:59:40.809Z", 
    "meta": [ 
     { 
      "_id": "594b6b072a8c4f294025e46f", 
      "post_id": "594b6adc2a8c4f294025e46e", 
      "views": 1, 
     }, 
     { 
      "_id": "594b6b1c2a8c4f294025e471", 
      "post_id": "594b6adc2a8c4f294025e46e", 
     } 
    ], 
}, 
{ 
    "_id": "594b6adc2a8c4f29402f465", 
    "title": "Test 2", 
    "created_at": "2017-06-22T06:59:40.809Z", 
    "meta": [ 
     { 
      "_id": "594b6b072a8c4f294025e46f", 
      "post_id": "594b6adc2a8c4f29402f465", 
      "views": 0, 
     }, 
     { 
      "_id": "594b6b1c2a8c4f294025e471", 
      "post_id": "594b6adc2a8c4f29402f465", 
     } 
    ], 
}, 
{ 
    "_id": "594b6adc2a8c4f29856d442", 
    "title": "Test 3", 
    "created_at": "2017-06-22T06:59:40.809Z", 
    "meta": [ 
     { 
      "_id": "594b6b072a8c4f294025e46f", 
      "post_id": "594b6adc2a8c4f29856d442", 
      "views": 3, 
     }, 
     { 
      "_id": "594b6b1c2a8c4f294025e471", 
      "post_id": "594b6adc2a8c4f29856d442", 
     } 
    ], 
} 

現在我想在這裏是基於這些結果進行排序「若干意見」「元」。喜歡的結果將按照'meta.views'的降序排列。第一結果將是元可欣賞= 3,然後視圖= 1個,然後視圖= 0

回答

2

$放鬆操作者分割的陣列到包含在陣列

對於例如爲每個對象單獨文件

db.collection.aggregate(

    // Pipeline 
    [ 


     // Stage 1 
     { 
      $unwind: { 
       path : "$meta" 
      } 
     }, 

     // Stage 2 
     { 
      $sort: { 
       'meta.views':-1 
      } 
     }, 

    ] 


); 
+0

感謝@RubinPorwal。你的回答可以幫助我80%。休息我還包括$組。 – Neeraj

+0

@neeraj你可以發表你的答案嗎? – user3542450