2016-12-26 62 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 });