Convert to BSON ObjectId or make a new one
967215
def oid(v = nil)
      return BSON::ObjectId.new if v.nil?; BSON::ObjectId.from_string(v) rescue v
    end
1235317
def cast_with_mongoid(object, type)
      cast = cast_without_mongoid(object, type)
      if defined?(::Mongoid::Document)
        if object.is_a?(Class) && object.ancestors.include?(::Mongoid::Document)
          cast = :mongoid_class
        elsif object.class.ancestors.include?(::Mongoid::Document)
          cast = :mongoid_document
        elsif (defined?(::BSON) && object.is_a?(::BSON::ObjectId)) || (defined?(::Moped::BSON) && object.is_a?(::Moped::BSON::ObjectId))
          cast = :mongoid_bson_id
        end
      end
      cast
    end
955634
def to_native(self, obj, name, value):  # pylint:disable=unused-argument
		""""""
		
		from marrow.mongo import Document
		from marrow.mongo.trait import Derived
		
		kind = self._kind(obj.__class__)
		
		if isinstance(value, Document):
			if __debug__ and kind and issubclass(kind, Document) and not isinstance(value, kind):
				raise ValueError("Not an instance of " + kind.__name__ + " or a sub-class: " + repr(value))
			
			return value
		
		if isinstance(kind, Field):
			return kind.transformer.native(value, (kind, obj))
		
		return (kind or Derived).from_mongo(value)
443864
function mongotocsv(options, callback) {
	if ( typeof(options) === null || typeof(options) === 'undefined' || !Object.keys(options).length){
		throw new Error('options are required, check the required options for mongotocsv');
		return;
	}
	
	if ( typeof(callback) === null || typeof(callback) === 'undefined' ){
		throw new Error('callback is required');
		return
	}

	// validate the options
	if( !options.hasOwnProperty('database') ){
		return callback('database name is required',null);
	} else if( typeof(options.database) !== 'string' ){
		return callback('database name must be string type',null);
	}

	if( !options.hasOwnProperty('collection') ){
		return callback('collection name is required',null);
	} else if( typeof(options.collection) !== 'string' ){
		return callback('collection name must be string type',null);
	}

	if( !options.hasOwnProperty('fields') ){
		return callback('fields name is required',null);
	} else if( typeof(options.fields) !== 'object' ){
		return callback('fields name must be array type',null);
	}

	if( !options.hasOwnProperty('output') ){
		return callback('output filepath is required and must be absolute',null);
	} else if( typeof(options.output) !== 'string' ){
		return callback('output filepath must be sting and absolute',null);
	}

	let arr = ['mongoexport', '--type=csv'],
	db 		= `-d ${options.database}`,
	coll 	= `-c ${options.collection}`,
	fields 	= `-f ${options.fields.join(',')}`,
	out 	= `-o ${options.output}`;
	if( options.hasOwnProperty('hostname') ){
		arr.push(`-h ${options.hostname}`);
	}
	if( options.hasOwnProperty('port') ){
		arr.push(`--port ${options.port}`);
	}
	if( options.hasOwnProperty('username') ){
		arr.push(`-u ${options.username}`);
	}
	if( options.hasOwnProperty('password') ){
		arr.push(`-p ${options.password}`);
	}
	if( options.hasOwnProperty('query') ){
		arr.push(`--query ${options.query}`);
	}
	
	if( options.hasOwnProperty('allValidOptions') ){
		arr.push(options.allValidOptions);
	}
	arr.push(db, coll, fields, out);
	let cmd = arr.join(" ");
	
	exec(cmd, (error, stdout, stderr) => {
		callback(error, stdout || stderr);  
	});
}
332714
function convertObject (schema, self) {
  var keys = Object.keys(schema);
  var ret = {};

  for (var i = 0; i < keys.length; ++i) {
    var key = keys[i];
    ret[key] = convertElement(schema[key], self);
  }

  return ret;
}
104350
def from_mongo(cls, data, expired=False, **kw):
		""""""
		
		value = super(Expires, cls).from_mongo(data, **kw)
		
		if not expired and value.is_expired:
			return None
		
		return value
961721
def cast_with_mongo_mapper(object, type)
      apply_default_mongo_mapper_options
      cast = cast_without_mongo_mapper(object, type)

      if defined?(::MongoMapper::Document)
        if object.is_a?(Class) && (object.ancestors & [::MongoMapper::Document, ::MongoMapper::EmbeddedDocument]).size > 0
          cast = :mongo_mapper_class
        elsif object.is_a?(::MongoMapper::Document) || object.is_a?(::MongoMapper::EmbeddedDocument)
          cast = :mongo_mapper_instance
        elsif object.is_a?(::MongoMapper::Plugins::Associations::Base)
          cast = :mongo_mapper_association
        elsif object.is_a?(::BSON::ObjectId)
          cast = :mongo_mapper_bson_id
        end
      end

      cast
    end
1337791
@SuppressWarnings("unchecked")
    public static org.bson.Document decodeMongoDoc(org.bson.Document doc) {
        org.bson.Document newDoc = new org.bson.Document();
        for (String key : doc.keySet()) {
            Object value = doc.get(key);
            if (value instanceof org.bson.Document)
                value = decodeMongoDoc(doc.get(key, org.bson.Document.class));
            else if (value instanceof List<?>) {
                for (int i=0; i < ((List<?>)value).size(); i++) {
                    Object obj = ((List<?>)value).get(i);
                    if (obj instanceof org.bson.Document)
                        ((List<org.bson.Document>)value).set(i, decodeMongoDoc((org.bson.Document)obj));
                }
            }

            String newKey = key;
            if (key.startsWith("\\uff04"))
                newKey = "$" + key.substring(6);
            if (key.contains("\\uff0e")) {
                newKey = newKey.replace("\\uff0e", ".");
            }
            newDoc.put(newKey, value);
        }
        return newDoc;
    }
26603
def update(collection_name, upsert, multi,
           spec, doc, safe, last_error_args, check_keys, opts):
    
    options = 0
    if upsert:
        options += 1
    if multi:
        options += 2

    data = _ZERO_32
    data += bson._make_c_string(collection_name)
    data += struct.pack("<i", options)
    data += bson.BSON.encode(spec, False, opts)
    encoded = bson.BSON.encode(doc, check_keys, opts)
    data += encoded
    if safe:
        (_, update_message) = __pack_message(2001, data)
        (request_id, error_message, _) = __last_error(collection_name,
                                                      last_error_args)
        return (request_id, update_message + error_message, len(encoded))
    else:
        (request_id, update_message) = __pack_message(2001, data)
        return (request_id, update_message, len(encoded))
892584
function Document(db, raw) 
{
  var self = this, raw;
  if (raw===undefined) raw = { };
  if (typeof(raw)==="string") raw = deserialize(raw);
  
  Object.defineProperty(this, "save", { value: function(cb) {
    return db.save(self, cb);
  }, writable: false  });

  Object.defineProperty(this, "remove", { value: function(cb) {
    if (! self._id) return cb(); // TODO maybe emit error
    return db.remove({ _id: self._id }, { }, cb);
  }, writable: false  });

  Object.defineProperty(this, "update", { value: function(modifier, cb) {
    if (self._id === undefined) self._id = db.createNewId();
    return db.update({ _id: self._id }, modifier, { upsert: true }, cb);
  }, writable: false  });

  Object.defineProperty(this, "copy", { value: function(strict) { 
    return deepCopy(self, strict);
  }, writable: false });

  Object.defineProperty(this, "serialize", { value: function(strict) {
    return serialize(self);
  }, writable: false });

  // Special methods
  for (var method in db._methods) Object.defineProperty(this, method, { value: db._methods[method], writable: false });

  // Persist to LevelUP
  Object.defineProperty(this, "_persist", { value: function(cb, quiet) {
    if (!quiet) db.emit("save", self);
    db.store.put(self._id, self.serialize(), function(err) {
      cb(err || null, err ? undefined : self);  
    });
  } });

  _.extend(this, raw.constructor.modelName ? deepCopy(raw) : raw); // Clone it deeply if it's schema-constructed
  schemas.construct(this, db.schema);
  db.emit("construct", self);
}
72839
function objectToArray(object) {
    var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'id';

    var convertedArray = [];

    Object.keys(object).forEach(function (_key) {
      var item = object[_key];
      item[key] = _key;
      convertedArray.push(item);
    });

    return convertedArray;
  }
294580
function(o, fields, callback) {
    
    var single, self = this;

    if (callback == null) {
      callback = fields;
      fields = null;
    } else if (fields instanceof Array) {
      fields = fields.reduce(function(ob, current) {
        ob[current] = 1;
        return ob;
      }, {});
    }

    if (typeof o == 'number' || typeof o == 'string' || o instanceof ObjectID) { 
      
      // If `o` is number: Convert to object
      o = {_id: o};
      single = true;
      
    } else if (o instanceof Array) {

      // If `o` is an array of params, process args recursively using multi
      var arr = o;
      var multi = this.multi();
      
      for (var i=0; i < arr.length; i++) {
        multi.get(arr[i], fields);
      }
      
      return multi.exec(function(err, docs) {
        docs = docs.filter(function(val) {
          return val; // Filter null values
        });
        callback.call(self, err, docs);
      });
      
    } else if (o.constructor === Object) {
      
      // IF `o` is object: Validate without checking required fields
      this.propertyCheck(o);

    } else {

      return callback.call(self, new Error(util.format("%s: Wrong value for `o` argument", this.className)), null);

    }
    
    // Convert `id` to `_id`
    convertMongoID(o);
    
    // Set single if ID is specified in query
    if (o._id) single = true; 
    
    this.driver.queryWhere({
      collection: this.context,
      condition: o,
      fields: fields || {},
      exArgs: {
        sort: [['_id', 'desc']]
      }
    }, function(err, docs) {
      if (err) callback.call(self, err, null);
      else {
        if (docs.length === 0) {
          callback.call(self, null, single ? null : []);
        } else if (single) {
          callback.call(self, null, self.createModel(docs[0]));
        } else {
          for (var models=[],i=0; i < docs.length; i++) {
            models.push(self.createModel(docs[i]));
          }
          callback.call(self, null, models);
        }
      }
    });
  }
1037971
def to_refs(value):
    """"""
    from mongoframes.frames import Frame, SubFrame

    # Frame
    if isinstance(value, Frame):
        return value._id

    # SubFrame
    elif isinstance(value, SubFrame):
        return to_refs(value._document)

    # Lists
    elif isinstance(value, (list, tuple)):
        return [to_refs(v) for v in value]

    # Dictionaries
    elif isinstance(value, dict):
        return {k: to_refs(v) for k, v in value.items()}

    return value
402756
function ObjectID(id) {
  // Duck-typing to support ObjectId from different npm packages
  if (id instanceof ObjectID) return id;
  if (!(this instanceof ObjectID)) return new ObjectID(id);

  this._bsontype = 'ObjectID';

  // The most common usecase (blank id, new objectId instance)
  if (id == null || typeof id === 'number') {
    // Generate a new id
    this.id = this.generate(id);
    // If we are caching the hex string
    if (ObjectID.cacheHexString) this.__id = this.toString('hex');
    // Return the object
    return;
  }

  // Check if the passed in id is valid
  var valid = ObjectID.isValid(id);

  // Throw an error if it's not a valid setup
  if (!valid && id != null) {
    throw new Error(
      'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
    );
  } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) {
    return new ObjectID(new Buffer(id, 'hex'));
  } else if (valid && typeof id === 'string' && id.length === 24) {
    return ObjectID.createFromHexString(id);
  } else if (id != null && id.length === 12) {
    // assume 12 byte string
    this.id = id;
  } else if (id != null && id.toHexString) {
    // Duck-typing to support ObjectId from different npm packages
    return id;
  } else {
    throw new Error(
      'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
    );
  }

  if (ObjectID.cacheHexString) this.__id = this.toString('hex');
}
506079
function toLink( data ) {
	if ( data && typeof data === 'object' ) {
		if ( data.constructor.name === 'ObjectID' || data.constructor.name === 'ObjectId' ) {
			return { _id: data } ;
		}

		data._id = toObjectId( data._id ) ;
	}
	else if ( typeof data === 'string' ) {
		try {
			data = { _id: mongodb.ObjectID( data ) } ;
		}
		catch ( error ) {}
	}

	return data ;
}
1358835
def rebuild_collection_tree(old_collection_ident, new_document_id_map, plpy):
    
    get_tree = plpy.prepare('''
    WITH RECURSIVE t(node, parent, document, title, childorder, latest, path)
        AS (SELECT tr.nodeid, tr.parent_id, tr.documentid, tr.title,
                   tr.childorder, tr.latest, ARRAY[tr.nodeid]
            FROM trees tr
            WHERE tr.documentid = $1 AND tr.is_collated = 'False'
    UNION ALL
        SELECT c.nodeid, c.parent_id, c.documentid, c.title,
               c.childorder, c.latest, path || ARRAY[c.nodeid]
        FROM trees c JOIN t ON (c.parent_id = t.node)
        WHERE not c.nodeid = ANY(t.path)
    )
    SELECT * FROM t
    ''', ('integer',))

    def get_old_tree():
        return plpy.execute(get_tree, (old_collection_ident,))

    tree = {}  # { old_nodeid: {'data': ...}, ...}
    children = {}  # { nodeid: [child_nodeid, ...], child_nodeid: [...]}
    for i in get_old_tree():
        tree[i['node']] = {'data': i, 'new_nodeid': None}
        children.setdefault(i['parent'], [])
        children[i['parent']].append(i['node'])

    insert_tree = plpy.prepare('''
    INSERT INTO trees (nodeid, parent_id, documentid,
        title, childorder, latest)
    VALUES (DEFAULT, $1, $2, $3, $4, $5)
    RETURNING nodeid
    ''', ('integer', 'integer', 'text', 'integer', 'boolean'))

    def execute(fields):
        results = plpy.execute(insert_tree, fields, 1)
        return results[0]['nodeid']

    root_node = children[None][0]

    def build_tree(node, parent):
        data = tree[node]['data']
        new_node = execute([parent, new_document_id_map.get(data['document'],
                            data['document']), data['title'],
                            data['childorder'], data['latest']])
        for i in children.get(node, []):
            build_tree(i, new_node)
    build_tree(root_node, None)
1095163
def to_foreign(self, obj, name, value):  # pylint:disable=unused-argument
		""""""
		
		if self.cache:
			return self._populate_cache(value)
		
		identifier = value
		
		# First, we handle the typcial Document object case.
		if isinstance(value, Document):
			identifier = value.__data__.get('_id', None)
			if identifier is None:
				raise ValueError("Can only store a reference to a saved Document instance with an `_id` stored.")
		
		elif isinstance(value, (str, unicode)) and len(value) == 24:
			try:
				identifier = OID(value)
			except InvalidId:
				pass
		
		kind = self._kind(obj.__class__)
		
		if self.concrete:
			if isinstance(value, Document) and value.__collection__:
				return DBRef(value.__collection__, identifier)
			
			if getattr(kind, '__collection__', None):
				return DBRef(kind.__collection__, identifier)
			
			raise ValueError("Could not infer collection name.")
		
		return identifier