二、Mongodb实战之——Mongodb Shell实现简单插入和查询

    • insert

    向集合中插入文档

    source code

    function (obj, _allow_dot) {
        if (!obj) {
            throw "no object passed to insert!";
        }
        if (!_allow_dot) {
            this._validateForStorage(obj);
        }
        if (typeof obj._id == "undefined" && !Array.isArray(obj)) {
            var tmp = obj;
            obj = {_id:new ObjectId};
            for (var key in tmp) {
                obj[key] = tmp[key];
            }
        }
        this._db._initExtraInfo();
        this._mongo.insert(this._fullName, obj);
        this._lastID = obj._id;
        this._db._getExtraInfo("Inserted");
    }
    

    example:

    >db.users.insert({"userName":"chjzh","pwd":"123"})
    

    • find

    在集合中查询符合条件的文档,find()返回集合中所有文档

    source code

    function (query, fields, limit, skip, batchSize, options) {
        return new DBQuery(this._mongo, this._db, this, this._fullName, this._massageObject(query), fields, limit, skip, batchSize, options || this.getQueryOptions());
    }
    

    example

    >db.users.find({"userName":"chjzh"})
    

    • save

    向集合中插入文档,与insert不同的是,若集合中存在重复的id则insert不做插入,而save则更改原来的内容为新内容

    source code

    function (obj) {
        if (obj == null || typeof obj == "undefined") {
            throw "can't save a null";
        }
        if (typeof obj == "number" || typeof obj == "string") {
            throw "can't save a number or string";
        }
        if (typeof obj._id == "undefined") {
            obj._id = new ObjectId;
            return this.insert(obj);
        } else {
            return this.update({_id:obj._id}, obj, true);
        }
    }
    

    example

    >db.users.save({"userName":"chjzh","pwd":"111111"})
    

    • count

    统计集合中满足条件的文档个数

    source code

    function (x) {
        return this.find(x).count();
    }
    

    example

    >db.users.count()
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值