2016-09-26 91 views
2

我試圖找到一個帶有Find()命令的整個文檔,並用條件過濾嵌套數組。貓鼬:查找和過濾嵌套數組

這裏一塊使用模式的:

var ListSH = new Schema({ 
    name: { type: String, unique: true, required: true}, 
    subject : String, 
    recipients : [ 
    Schema({ 
    uid : { type : ObjectId, required : true, ref:'User', unique: true}, 
    status : { type : Number, default : 1 } 
    },{_id: false}) 
    ] 
}; 

目前我做ListModel.findOne({ _id : req.params.id_list, function(err,list){...};

和送信給我說:

{ 
    "_id": "57e6bcab6b383120f0395aed", 
    "name": "Emailing listname", 
    "subject": "List subject", 
    "recipients": [ 
    { 
     "uid": "57e932bcbbf0e9e543def600", 
     "status": 0 
    }, 
    { 
     "uid": "57e93266c3c0b1dc1625986f", 
     "status": 1 
    } 
    ] 
} 

我想郵差回到我喜歡的東西即通過加入recipients.status : 1條件

{ 
     "_id": "57e6bcab6b383120f0395aed", 
     "name": "Emailing listname", 
     "subject": "List subject", 
     "recipients": [ 
     { 
      "uid": "57e93266c3c0b1dc1625986f", 
      "status": 1 
     } 
     ] 
    } 

我已經嘗試過ListModel.findOne({ _id : req.params.id_list, 'recipients.status' : 1}, function(err,list){...};

和奇怪的東西像populate([$match('recipients.status : 1)]); 但沒有成功..

有誰知道? 謝謝^^

回答

1

您可以使用aggregate得到它在一個簡單的方法是這樣

ListModel.aggregate(
    { $match: {_id: ObjectId("57e6bcab6b383120f0395aed")}}, 
    { $unwind: '$recipients'}, 
    { $match: {'recipients.status':1}}) 

輸出

{ 
    "_id" : ObjectId("57e6bcab6b383120f0395aed"), 
    "name" : "Emailing listname", 
    "subject" : "List subject", 
    "recipients" : { 
     "uid" : "57e93266c3c0b1dc1625986f", 
     "status" : 1 
    } 
} 

要詳細瞭解彙總,請參閱文檔s here

+0

這隻會返回一個$收件人,無論有多少條回答標準。 – Vaiden

0

試試下面的查詢:

ListModel.findOne({"_id" : "57e6bcab6b383120f0395aed", 'recipients.status' : 1},{_id:1, name: 1, subject:1,'recipients.$': 1}, function(err,list){...}); 
+0

這兩種解決方案都適合我! 非常感謝您的幫助 –

+0

@ nicolas.grd很高興它幫助! – Sachin