2014-03-01 34 views
-1

我想根據幾個條件查詢文檔,然後只保留特定的字段。下面的查詢(mongoskin語法)返回待辦事項當前用戶,並通過標籤過濾:在多個條件下投影查找查詢

db.collection('users').find({ 
    _id : db.bson_serializer.ObjectID.createFromHexString(req.user._id.toString()) 
}, { 
    todos : { 
     $elemMatch : { 
      tags : filterTag 
     } 
    } 
} 

然後我試圖添加投影,但過濾不再進行。

db.collection('users').find({ 
    _id : db.bson_serializer.ObjectID.createFromHexString(req.user._id.toString()), 
    todos : { 
     $elemMatch : { 
      tags : filterTag 
     } 
    } 
}, { 
    _id : 0, 
    'todos.value' : 1, 
    'todos._id' : 1 
} 

回答

0

我居然發現與骨料的解決方案:

db.collection('users').aggregate({ 
    $unwind : '$todos' 
}, { 
    $match : { 
     _id : db.bson_serializer.ObjectID.createFromHexString(req.user._id.toString()), 
     'todos.tags' : filterTag 
    } 
}, { 
    $project : { 
     _id : 0, 
     'todos.value' : 1, 
     'todos._id' : 1 
    } 
}