2017-04-21 20 views
2

我正在使用貓鼬來處理MongoDB。如果未找到值,則使用貓鼬將對象添加到數組,否則更新字段

我有以下文件

Posts:Array 
    0:Object 
     _id:58f9b2c903110b2c543fb7d1 
     postName:Test1 
     postText:Test2 
     postCount:0 
     status:true 

我想這樣做一個HTTP請求以更新或插入的對象到這個數組基於postName。

例如,如果我通過了以下

{ 
    postName:Test1 
    postText:Test3 
    postCount:50 
    status:false 
} 

比postName比賽,我想它只是更新postText,postCount和狀態。 如果postName不匹配數組中的任何一個對象,我希望它插入一個新的對象。

這個問題可能重複舊的問題,我搜索了,我找不到答案。 我也嘗試使用$ setOnInsert,但無法讓它工作。

+0

使用此'分貝。 collection.update( , , { upsert:true } )' –

+0

什麼是?我怎樣才能讓它基於postName?由於 –

+0

db.collection.update({postName:測試1},{ postName:Test1的 postText:Test3的 postCount:50種 狀態:假 },{UPSERT:真}) –

回答

相關問題