/** * Save current object to MongoDB * * @param boolean $refresh Should refresh the object fields values? * @return boolean */ function save($refresh = false) { if (!$this->_collection) { import("@.RMongoException"); throw new RMongoException("Object is not in any collection, please use setCollection() to method to set a collection."); } $bool = true; if ($this->_id) { //if exists if (!empty($this->_operations)) { $bool = $this->_collection->update(array("_id" => $this->_id), $this->_operations, array("upsert" => false, "multiple" => false)); if ($refresh) { $bool = $this->refresh(); } } } else { $bool = $this->_collection->insert($this->_attrs, true); if ($bool) { $this->_id = $this->_attrs["_id"]; import("@.RMongo"); RMongo::setLastInsertId($this->_id->__toString()); } } $this->_operations = array(); return $bool; }
/** * 插入新的行,_id是上一行的ID加1 * * @param array $attrs 新行的属性集 * @return boolean */ function insertNext(array $attrs) { $response = $this->_db->execute('function insertObject(o, myCollection) { var x = db.getCollection(myCollection); while( 1 ) { // determine next _id value to try var c = x.find({},{_id:1}).sort({_id:-1}).limit(1); var i = c.hasNext() ? c.next()._id + 1 : 1; o._id = i; x.insert(o); var err = db.getLastErrorObj(); if( err && err.code ) { if( err.code == 11000 /* dup key */ ) continue; else print("unexpected error inserting data: " + tojson(err)); } break; } return o._id; }', array($attrs, $this->_collectionName)); if ($response["ok"]) { import("@.RMongo"); RMongo::setLastInsertId($response["retval"]); } return $response["ok"]; }