2013-09-24 115 views
1

我正在使用Mongoose,我試圖更新一個數組元素並將其更新。 這是我的文檔結構:Mongodb:使用findOneAndUpdate的數組元素投影不起作用?

{ name:String, 
    friends:[ 
     { name:String, 
      age:Number 
     } 
    ] 
} 

當我執行以下查詢我得到的結果所有的朋友,但我只希望得到25歲的網友回覆:

theCollection.findOneAndUpdate(
    { name : 'cherif', 
     'friends.name':'kevin' 
    }, 
    { $set:{ 
      'friends.$.age':25 
     } 
    }, 
    { friends: 
     { $elemMatch: 
      { age : 25 } 
     } 
    }, 
    function(err,result){ 
     if (!err) { 
      console.log(result); 
     }}); 

回答

5

至於the docsfindOneAndUpdate指定,你需要包括你的投影對象作爲參數optionsselect屬性:

theCollection.findOneAndUpdate(
    { name : 'cherif', 
     'friends.name':'kevin' 
    }, 
    { $set:{ 
      'friends.$.age':25 
     } 
    }, 
    { select: { 
      friends: { 
       $elemMatch: 
       { age : 25 } 
      } 
     } 
    }, 
    function(err,result){ 
     if (!err) { 
      console.log(result); 
     } 
    }); 
+3

我有可能在這裏使用$投影嗎?例如'Doc.findOneAndUpdate({_id:id,'comments._id':cmtId},{...},{select:'comments。$':1})'。我嘗試了這個,但奇怪的是它返回了{{評論:[{},{},{}],_id:...} – KwiZ

+0

@KwiZ你有沒有找到這個解決方案?我試圖以相同的方式使用$投影,但沒有運氣! – admrply

+0

@admrply繼續併發佈一個新問題,並提供有關您要做什麼的完整詳細信息。 – JohnnyHK