2016-05-24 33 views
2

我有一個域 「通知」排序情況下MongoDB中

{ 
    _id: 1 
    is_action: false, 
    user:[{ 
     user_id: 5, 
     status: "R" 
    }, 
    { 
     user_id: 8, 
     status: "U" 
    }], 
    priority:1  
}, 
{ 
    _id: 2 
    is_action: true, 
    user:[{ 
     user_id: 5, 
     status: "U" 
    }, 
    { 
     user_id: 8, 
     status: "U" 
    }], 
    priority:1  
} 

我的查詢來查找通知,其中USER_ID = 5 ------

db.notifications.aggregate([ 
    {$unwind:"$user"}, 
    {$match:{ 
     "user.user_id":5, 
     is_action: false 
    }}, 
    {$sort:{priority:1}} 
]) 

但我需要排序根據以下條件進行上述查詢

if(status == "U"){ 
    Sort by "priority" 
}else{ 
    Sort by "_id" 
} 

回答

2

使用$cond創建一個新字段,例如

{ $project: { otherfield: 1, sortField: { $cond: { if: { $eq: [ "$status","U" ] }, then: "$priority", else: "$_id" } } } }

然後排序這個領域。

P.S. $ cond是MongoDB版本2.6以上的新操作符

+0

您可以嘗試使用MongoDB GUI,它可以更輕鬆地解決您的問題。嘗試http://mongobooster.com,它是免費的非商業。 –

相關問題