日期:2014-05-16 浏览次数:20399 次
向集合中插入文档
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"); }
>db.users.insert({"userName":"chjzh","pwd":"123"})
在集合中查询符合条件的文档,find()返回集合中所有文档
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()); }
>db.users.find({"userName":"chjzh"})
向集合中插入文档,与insert不同的是,若集合中存在重复的id则insert不做插入,而save则更改原来的内容为新内容
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); } }
>db.users.save({"userName":"chjzh","pwd":"111111"})
统计集合中满足条件的文档个数
function (x) { return this.find(x).count(); }
>db.users.count()