2016-12-26 16 views
3

這是我目前擁有的文件:推對象轉換成數組,如果存在,否則設置對象MongoDB中

{ 
    "_id": "", 
    "title": "My Watchlist", 
    "series": [{ 
     "seriesId": 1, 
     "following": true, 
     "seasons": [] 
    }, { 
     "seriesId": 1, 
     "following": false, 
     "seasons": [] 
    }] 
} 

正如你可以看到目前有2個對象與seriesId 1,但有不同的以下布爾。

如果查詢與_id相匹配,它應該將新對象推入系列,如果在「系列」 - 陣列中具有相同「seriesId」的對象已經存在,它應該更改該對象內的字段,而不是添加新對象。

目前,我有以下查詢:

users.update(
    {"_id": req.body.userId}, 
    { 
     "$push": { 
      "series": {"seriesId": req.body.seriesId, "following": req.body.following} 
     } 
    }, (err, data) => { 
     if (err) 
      next(err); 
    }); 

如果我使用$設置不添加的對象,如果它沒有淵源存在着呢,據我知道你不能同時使用$推和$設置? 可以以任何方式解決這個問題嗎?還是必須重新考慮我的模式?

+0

可能重複[可以mongo upsert數組數據嗎?](http://stackoverflow.com/questions/13588342/can-mongo-upsert-array-data) – MYGz

回答

2

您可以使用兩種update查詢:

  • 如果_id被發現,seriesId是不是數組中,新項目添加到陣列:

    db.series.update({ 
        "_id": req.body.userId, 
        "series": { 
         "$not": { 
          "$elemMatch": { 
           "seriesId": req.body.seriesId 
          } 
         } 
        } 
    }, { 
        $addToSet: { 
         series: { 
          "seriesId": req.body.seriesId, 
          "following": req.body.following, 
          "seasons": [] 
         } 
        } 
    }, { multi: true }); 
    
  • 如果_id被發現並在陣列中找到seriesId,更新數組項目:

    db.series.update({ 
        "_id": req.body.userId, 
        "series.seriesId": req.body.seriesId 
    }, { 
        $set: { 
         "series.$.following": req.body.following 
        } 
    }, { multi: true });