日期:2014-05-16  浏览次数:20482 次

三、Mongodb实战之——Mongodb Shell实现简单更新

  1. update
  2. 所有的更新操作都要求至少两个参数,第一个指明要更新的文档,第二个定义被选中的文档应该如何更新

    第四个参数指定是否执行多项更新,MongoDB的更新操作默认只应用于查询选择器匹配到的第一个文档

    source code

    function (query, obj, upsert, multi) {
        assert(query, "need a query");
        assert(obj, "need an object");
        var firstKey = null;
        for (var k in obj) {
            firstKey = k;
            break;
        }
        if (firstKey != null && firstKey[0] == "$") {
            this._validateObject(obj);
        } else {
            this._validateForStorage(obj);
        }
        if (typeof upsert === "object") {
            assert(multi === undefined, "Fourth argument must be empty when specifying upsert and multi with an object.");
            opts = upsert;
            multi = opts.multi;
            upsert = opts.upsert;
        }
        this._db._initExtraInfo();
        this._mongo.update(this._fullName, query, obj, upsert ? true : false, multi ? true : false);
        this._db._getExtraInfo("Updated");
    }
    	

    example

    db.users.update({"pwd":"111111"},{$set:{userName:"bychjzh"}})
    	

  3. $set
  4. 修改某个属性要使用$set

    example

    同上:
     db.users.update({"pwd":"111111"},{$set:{userName:"bychjzh"}})
    	

  5. $unset
  6. 删除某个属性使用$unset

    example

    db.users.update({"pwd":"111111"},{$unset:{userName:1}})
    	

  7. $push
  8. $push可以向数组中添加一个元素

    example

    > db.users.insert({"userName":"chjzh","pwd":"111","hobbies":["music","listening"]})
    > db.users.find()
    { "_id" : ObjectId("513dad1d5a5c6b621c993e74"), "userName" : "chjzh", "pwd" : "123" }
    { "_id" : ObjectId("51428d3c2540dc509d6d3572"), "pwd" : "111111" }
    { "_id" : ObjectId("5143df5d0d5983f976e05adf"), "userName" : "chjzh", "pwd" : "111", "hobbies" : [ "music", "listening" ] }
    > db.users.update({"pwd":"111"},{$push:{"hobbies":"table tenis"}},false,true)
    > db.users.find()
    { "_id" : ObjectId("513dad1d5a5c6b621c993e74"), "userName" : "chjzh", "pwd" : "123" }
    { "_id" : ObjectId("51428d3c2540dc509d6d3572"), "pwd" : "111111" }
    { "_id" : ObjectId("5143df5d0d5983f976e05adf"), "hobbies" : [ "music", "listening", "table tenis" ], "pwd" : "111", "userName" : "chjzh" }
    	

  9. $addToSet
  10. $addToSet同样可以向数组中添加元素,与$push不同的是$addToSet会保证元素的唯一性,防止重复添加

    example

    > db.users.update({"pwd":"111"},{$addToSet:{"hobbies":"table tenis"}},false,true)
    > db.users.update({"pwd":"111"},{$addToSet:{"hobbies":"basketball"}},false,true)
    > db.users.find()
    { "_id" : ObjectId("513dad1d5a5c6b621c993e74"), "userName" : "chjzh", "pwd" : "123" }
    { "_id" : ObjectId("51428d3c2540dc509d6d3572"), "pwd" : "111111" }
    { "_id" : ObjectId("5143df5d0d5983f976e05adf"), "hobbies" : [ "music", "listening", "table tenis", "basketball" ], "pwd" : "111", "userName" : "chjzh" }