Mongodb数组$ push和$ pull

san*_*osh 16 mongodb

我想从数组中提取一些值并同时尝试更新它.

    userSchema.statics.experience = function (id,xper,delet,callback) {
    var update = {
      $pull:{
        'profile.experience' : delet
      },

        $push: {
          'profile.experience': xper
        }
  };
  this.findByIdAndUpdate(id,update,{ 'new': true},function(err,doc) {
    if (err) {
      callback(err);
    } else if(doc){
      callback(null,doc);
    }
  });
};
Run Code Online (Sandbox Code Playgroud)

我得到的错误就像 MongoError: exception: Cannot update 'profile.experience' and 'profile.experience' at the same time

Vla*_*ski 10

我找到了这个解释:

问题是MongoDB不允许在同一更新调用中对同一属性进行多个操作.这意味着这两个操作必须在两个单独的原子操作中发生.

你可以阅读那些帖子:

使用mongo同时拉和添加

多个mongo更新运算符在一个语句中?


Nik*_*yev 10

如果您需要将一个数组值替换为另一个,您可以使用arrayFilters进行更新。

(至少,存在于 mongo 4.2.1)。

db.your_collection.update(
    { "_id": ObjectId("your_24_byte_length_id") },
    { "$set": { "profile.experience.$[elem]": "new_value" } },
    { "arrayFilters": [ { "elem": { "$eq": "old_value" } } ], "multi": true }
) 
Run Code Online (Sandbox Code Playgroud)

这将用“new_value”替换所有“old_value”数组元素。