0
0
mirror of https://github.com/mongodb/mongo.git synced 2024-11-30 17:10:48 +01:00
mongodb/shell/collection.js

570 lines
16 KiB
JavaScript
Raw Normal View History

2009-01-27 04:19:15 +01:00
// collection.js
if ( ( typeof DBCollection ) == "undefined" ){
DBCollection = function( mongo , db , shortName , fullName ){
this._mongo = mongo;
this._db = db;
this._shortName = shortName;
this._fullName = fullName;
2009-07-21 20:41:23 +02:00
2009-05-05 16:43:38 +02:00
this.verify();
2009-01-27 04:19:15 +01:00
}
}
2009-05-05 16:43:38 +02:00
DBCollection.prototype.verify = function(){
assert( this._fullName , "no fullName" );
assert( this._shortName , "no shortName" );
assert( this._db , "no db" );
2009-07-21 20:41:23 +02:00
2009-05-05 16:43:38 +02:00
assert.eq( this._fullName , this._db._name + "." + this._shortName , "name mismatch" );
assert( this._mongo , "no mongo in DBCollection" );
2009-05-05 16:43:38 +02:00
}
2009-01-27 04:19:15 +01:00
DBCollection.prototype.getName = function(){
return this._shortName;
}
DBCollection.prototype.help = function(){
print("DBCollection help");
2009-10-16 19:54:06 +02:00
print("\tdb.foo.count()");
print("\tdb.foo.dataSize()");
2009-10-27 16:52:37 +01:00
print("\tdb.foo.distinct( key ) - eg. db.foo.distinct( 'x' )" );
2009-10-16 19:54:06 +02:00
print("\tdb.foo.drop() drop the collection");
print("\tdb.foo.dropIndex(name)");
print("\tdb.foo.dropIndexes()");
print("\tdb.foo.ensureIndex(keypattern,options) - options should be an object with these possible fields: name, unique, dropDups");
2009-10-07 20:42:46 +02:00
print("\tdb.foo.find( [query] , [fields]) - first parameter is an optional query filter. second parameter is optional set of fields to return.");
print("\t e.g. db.foo.find( { x : 77 } , { name : 1 , x : 1 } )");
2009-10-16 19:54:06 +02:00
print("\tdb.foo.find(...).count()");
2009-01-27 04:19:15 +01:00
print("\tdb.foo.find(...).limit(n)");
print("\tdb.foo.find(...).skip(n)");
2009-10-16 19:54:06 +02:00
print("\tdb.foo.find(...).sort(...)");
print("\tdb.foo.findOne([query])");
2009-12-31 02:08:43 +01:00
print("\tdb.foo.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )");
2009-10-16 19:54:06 +02:00
print("\tdb.foo.getDB() get DB object associated with collection");
print("\tdb.foo.getIndexes()");
2009-08-24 17:42:15 +02:00
print("\tdb.foo.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )");
2009-10-27 16:52:37 +01:00
print("\tdb.foo.mapReduce( mapFunction , reduceFunction , <optional params> )" );
2009-09-09 22:52:02 +02:00
print("\tdb.foo.remove(query)" );
2009-12-28 19:10:39 +01:00
print("\tdb.foo.renameCollection( newName , <dropTarget> ) renames the collection.");
2009-10-16 19:54:06 +02:00
print("\tdb.foo.save(obj)");
2009-08-12 19:53:52 +02:00
print("\tdb.foo.stats()");
print("\tdb.foo.storageSize() - includes free space allocated to this collection");
print("\tdb.foo.totalIndexSize() - size in bytes of all the indexes");
2009-10-07 20:42:46 +02:00
print("\tdb.foo.totalSize() - storage allocated for all data and indexes");
2009-12-10 03:29:59 +01:00
print("\tdb.foo.update(query, object[, upsert_bool, multi_bool])");
2009-10-16 19:54:06 +02:00
print("\tdb.foo.validate() - SLOW");
print("\tdb.foo.getShardVersion() - only for use with sharding" );
2009-01-27 04:19:15 +01:00
}
DBCollection.prototype.getFullName = function(){
return this._fullName;
}
DBCollection.prototype.getDB = function(){
return this._db;
}
DBCollection.prototype._dbCommand = function( cmd ){
return this._db._dbCommand( cmd );
}
DBCollection.prototype._massageObject = function( q ){
if ( ! q )
return {};
var type = typeof q;
2009-07-21 20:41:23 +02:00
2009-01-27 04:19:15 +01:00
if ( type == "function" )
return { $where : q };
2009-07-21 20:41:23 +02:00
2009-01-27 04:19:15 +01:00
if ( q.isObjectId )
return { _id : q };
2009-07-21 20:41:23 +02:00
2009-01-27 04:19:15 +01:00
if ( type == "object" )
return q;
2009-07-21 20:41:23 +02:00
2009-01-27 04:19:15 +01:00
if ( type == "string" ){
if ( q.length == 24 )
return { _id : q };
2009-07-21 20:41:23 +02:00
2009-01-29 21:58:54 +01:00
return { $where : q };
2009-01-27 04:19:15 +01:00
}
throw "don't know how to massage : " + type;
2009-07-21 20:41:23 +02:00
2009-01-27 04:19:15 +01:00
}
2009-06-24 20:49:50 +02:00
DBCollection.prototype._validateObject = function( o ){
if ( o._ensureSpecial && o._checkModify )
throw "can't save a DBQuery object";
}
2009-08-10 17:10:15 +02:00
DBCollection._allowedFields = { $id : 1 , $ref : 1 };
2009-01-27 04:19:15 +01:00
DBCollection.prototype._validateForStorage = function( o ){
2009-06-24 20:49:50 +02:00
this._validateObject( o );
2009-03-27 21:12:06 +01:00
for ( var k in o ){
if ( k.indexOf( "." ) >= 0 ) {
2009-01-27 04:19:15 +01:00
throw "can't have . in field names [" + k + "]" ;
}
2009-08-10 17:10:15 +02:00
if ( k.indexOf( "$" ) == 0 && ! DBCollection._allowedFields[k] ) {
throw "field names cannot start with $ [" + k + "]";
}
if ( o[k] !== null && typeof( o[k] ) === "object" ) {
this._validateForStorage( o[k] );
}
2009-01-27 04:19:15 +01:00
}
};
2009-01-27 04:19:15 +01:00
2009-06-24 20:49:50 +02:00
2009-01-27 04:19:15 +01:00
DBCollection.prototype.find = function( query , fields , limit , skip ){
2009-07-21 20:41:23 +02:00
return new DBQuery( this._mongo , this._db , this ,
2009-01-27 04:19:15 +01:00
this._fullName , this._massageObject( query ) , fields , limit , skip );
}
DBCollection.prototype.findOne = function( query , fields ){
var cursor = this._mongo.find( this._fullName , this._massageObject( query ) || {} , fields , -1 , 0 );
2009-01-27 04:19:15 +01:00
if ( ! cursor.hasNext() )
return null;
var ret = cursor.next();
if ( cursor.hasNext() ) throw "findOne has more than 1 result!";
2009-01-27 04:19:15 +01:00
if ( ret.$err )
throw "error " + tojson( ret );
return ret;
}
DBCollection.prototype.insert = function( obj , _allow_dot ){
2009-01-27 04:19:15 +01:00
if ( ! obj )
2009-11-20 03:40:11 +01:00
throw "no object passed to insert!";
if ( ! _allow_dot ) {
this._validateForStorage( obj );
}
2009-02-06 18:31:24 +01:00
return this._mongo.insert( this._fullName , obj );
2009-01-27 04:19:15 +01:00
}
DBCollection.prototype.remove = function( t ){
this._mongo.remove( this._fullName , this._massageObject( t ) );
}
DBCollection.prototype.update = function( query , obj , upsert , multi ){
2009-01-27 04:19:15 +01:00
assert( query , "need a query" );
assert( obj , "need an object" );
2009-06-24 20:49:50 +02:00
this._validateObject( obj );
this._mongo.update( this._fullName , query , obj , upsert ? true : false , multi ? true : false );
2009-01-27 04:19:15 +01:00
}
DBCollection.prototype.save = function( obj ){
2009-08-28 18:34:56 +02:00
if ( obj == null || typeof( obj ) == "undefined" )
throw "can't save a null";
2009-05-14 22:39:10 +02:00
if ( typeof( obj._id ) == "undefined" ){
obj._id = new ObjectId();
2009-02-06 18:31:24 +01:00
return this.insert( obj );
2009-01-27 04:19:15 +01:00
}
else {
2009-02-06 18:31:24 +01:00
return this.update( { _id : obj._id } , obj , true );
2009-01-27 04:19:15 +01:00
}
}
DBCollection.prototype._genIndexName = function( keys ){
var name = "";
2009-03-27 21:12:06 +01:00
for ( var k in keys ){
var v = keys[k];
if ( typeof v == "function" )
continue;
2009-01-27 04:19:15 +01:00
if ( name.length > 0 )
name += "_";
name += k + "_";
if ( typeof v == "number" )
name += v;
}
return name;
}
DBCollection.prototype._indexSpec = function( keys, options ) {
var ret = { ns : this._fullName , key : keys , name : this._genIndexName( keys ) };
if ( ! options ){
}
else if ( typeof ( options ) == "string" )
ret.name = options;
else if ( typeof ( options ) == "boolean" )
ret.unique = true;
else if ( typeof ( options ) == "object" ){
if ( options.length ){
var nb = 0;
for ( var i=0; i<options.length; i++ ){
if ( typeof ( options[i] ) == "string" )
ret.name = options[i];
else if ( typeof( options[i] ) == "boolean" ){
if ( options[i] ){
if ( nb == 0 )
ret.unique = true;
if ( nb == 1 )
ret.dropDups = true;
}
nb++;
}
}
}
else {
Object.extend( ret , options );
}
}
else {
throw "can't handle: " + typeof( options );
}
/*
return ret;
var name;
var nTrue = 0;
if ( ! isObject( options ) ) {
options = [ options ];
}
if ( options.length ){
for( var i = 0; i < options.length; ++i ) {
var o = options[ i ];
if ( isString( o ) ) {
ret.name = o;
} else if ( typeof( o ) == "boolean" ) {
if ( o ) {
++nTrue;
}
}
}
if ( nTrue > 0 ) {
ret.unique = true;
}
if ( nTrue > 1 ) {
ret.dropDups = true;
}
}
*/
return ret;
}
DBCollection.prototype.createIndex = function( keys , options ){
var o = this._indexSpec( keys, options );
this._db.getCollection( "system.indexes" ).insert( o , true );
2009-01-27 04:19:15 +01:00
}
DBCollection.prototype.ensureIndex = function( keys , options ){
var name = this._indexSpec( keys, options ).name;
2009-01-27 04:19:15 +01:00
this._indexCache = this._indexCache || {};
if ( this._indexCache[ name ] ){
2009-10-20 22:20:22 +02:00
return;
}
2009-01-27 04:19:15 +01:00
this.createIndex( keys , options );
if ( this.getDB().getLastError() == "" ) {
this._indexCache[name] = true;
}
2009-01-27 04:19:15 +01:00
}
DBCollection.prototype.resetIndexCache = function(){
this._indexCache = {};
}
2009-02-09 19:05:36 +01:00
DBCollection.prototype.reIndex = function(){
var specs = this.getIndexSpecs();
2009-02-09 19:05:36 +01:00
this.dropIndexes();
2009-04-20 20:32:41 +02:00
for ( var i = 0; i < specs.length; ++i ){
this.ensureIndex( specs[i].key, [ specs[i].unique, specs[i].name ] );
2009-02-09 19:05:36 +01:00
}
}
DBCollection.prototype.dropIndexes = function(){
2009-01-27 04:19:15 +01:00
this.resetIndexCache();
var res = this._db.runCommand( { deleteIndexes: this.getName(), index: "*" } );
assert( res , "no result from dropIndex result" );
if ( res.ok )
return res;
2009-07-21 20:41:23 +02:00
2009-01-27 04:19:15 +01:00
if ( res.errmsg.match( /not found/ ) )
return res;
throw "error dropping indexes : " + tojson( res );
}
DBCollection.prototype.drop = function(){
this.resetIndexCache();
var ret = this._db.runCommand( { drop: this.getName() } );
2009-11-09 19:10:30 +01:00
if ( ! ret.ok ){
if ( ret.errmsg == "ns not found" )
return false;
throw "drop failed: " + tojson( ret );
2009-11-09 19:10:30 +01:00
}
return true;
2009-01-27 04:19:15 +01:00
}
2009-12-31 02:08:43 +01:00
DBCollection.prototype.findAndModify = function(args){
var cmd = { findandmodify: this.getName() };
for (key in args){
cmd[key] = args[key];
}
var ret = this._db.runCommand( cmd );
if ( ! ret.ok ){
if (ret.errmsg == "No matching object found"){
return {};
}
throw "findAndModifyFailed failed: " + tojson( ret.errmsg );
}
return ret.value;
}
DBCollection.prototype.renameCollection = function( newName , dropTarget ){
return this._db._adminCommand( { renameCollection : this._fullName ,
to : this._db._name + "." + newName ,
dropTarget : dropTarget } )
2009-09-07 17:14:48 +02:00
}
2009-01-27 04:19:15 +01:00
DBCollection.prototype.validate = function() {
var res = this._db.runCommand( { validate: this.getName() } );
2009-07-21 20:41:23 +02:00
2009-01-27 04:19:15 +01:00
res.valid = false;
if ( res.result ){
var str = "-" + tojson( res.result );
res.valid = ! ( str.match( /exception/ ) || str.match( /corrupt/ ) );
var p = /lastExtentSize:(\d+)/;
var r = p.exec( str );
if ( r ){
res.lastExtentSize = Number( r[1] );
}
}
2009-07-21 20:41:23 +02:00
2009-01-27 04:19:15 +01:00
return res;
}
DBCollection.prototype.getShardVersion = function(){
return this._db._adminCommand( { getShardVersion : this._fullName } );
}
2009-01-27 04:19:15 +01:00
DBCollection.prototype.getIndexes = function(){
return this.getDB().getCollection( "system.indexes" ).find( { ns : this.getFullName() } ).toArray();
2009-01-27 04:19:15 +01:00
}
2009-05-17 03:01:56 +02:00
DBCollection.prototype.getIndices = DBCollection.prototype.getIndexes;
2009-05-19 16:54:06 +02:00
DBCollection.prototype.getIndexSpecs = DBCollection.prototype.getIndexes;
2009-05-17 03:01:56 +02:00
2009-05-19 16:54:06 +02:00
DBCollection.prototype.getIndexKeys = function(){
2009-07-21 20:41:23 +02:00
return this.getIndexes().map(
2009-01-27 04:19:15 +01:00
function(i){
2009-05-19 16:54:06 +02:00
return i.key;
2009-01-27 04:19:15 +01:00
}
);
}
2009-05-11 22:38:15 +02:00
DBCollection.prototype.count = function( x ){
return this.find( x ).count();
2009-01-27 04:19:15 +01:00
}
/**
* Drop free lists. Normally not used.
* Note this only does the collection itself, not the namespaces of its indexes (see cleanAll).
*/
DBCollection.prototype.clean = function() {
return this._dbCommand( { clean: this.getName() } );
}
/**
* <p>Drop a specified index.</p>
*
* <p>
* Name is the name of the index in the system.indexes name field. (Run db.system.indexes.find() to
* see example data.)
* </p>
*
* <p>Note : alpha: space is not reclaimed </p>
* @param {String} name of index to delete.
* @return A result object. result.ok will be true if successful.
*/
DBCollection.prototype.dropIndex = function(index) {
assert(index , "need to specify index to dropIndex" );
2009-07-21 20:41:23 +02:00
2009-01-27 04:19:15 +01:00
if ( ! isString( index ) && isObject( index ) )
index = this._genIndexName( index );
2009-07-21 20:41:23 +02:00
2009-01-27 04:19:15 +01:00
var res = this._dbCommand( { deleteIndexes: this.getName(), index: index } );
this.resetIndexCache();
return res;
}
2009-03-06 22:44:16 +01:00
DBCollection.prototype.copyTo = function( newName ){
2009-07-21 20:41:23 +02:00
return this.getDB().eval(
2009-03-06 22:44:16 +01:00
function( collName , newName ){
var from = db[collName];
var to = db[newName];
to.ensureIndex( { _id : 1 } );
var count = 0;
2009-07-21 20:41:23 +02:00
2009-03-06 22:44:16 +01:00
var cursor = from.find();
while ( cursor.hasNext() ){
var o = cursor.next();
count++;
to.save( o );
}
2009-07-21 20:41:23 +02:00
2009-03-06 22:44:16 +01:00
return count;
2009-07-21 20:41:23 +02:00
} , this.getName() , newName
2009-03-06 22:44:16 +01:00
);
}
2009-01-27 04:19:15 +01:00
DBCollection.prototype.getCollection = function( subName ){
return this._db.getCollection( this._shortName + "." + subName );
}
2009-05-17 03:01:56 +02:00
DBCollection.prototype.stats = function(){
2009-08-12 19:53:52 +02:00
return this._db.runCommand( { collstats : this._shortName } );
2009-05-17 03:01:56 +02:00
}
DBCollection.prototype.dataSize = function(){
2009-08-12 19:53:52 +02:00
return this.stats().size;
}
DBCollection.prototype.storageSize = function(){
return this.stats().storageSize;
2009-05-17 03:01:56 +02:00
}
DBCollection.prototype.totalIndexSize = function( verbose ){
2009-05-17 03:01:56 +02:00
var total = 0;
var mydb = this._db;
var shortName = this._shortName;
this.getIndexes().forEach(
function( spec ){
var coll = mydb.getCollection( shortName + ".$" + spec.name );
var mysize = coll.dataSize();
total += coll.dataSize();
if ( verbose ) {
print( coll + "\t" + mysize );
}
2009-05-17 03:01:56 +02:00
}
);
return total;
}
2009-08-24 23:13:15 +02:00
DBCollection.prototype.totalSize = function(){
var total = this.storageSize();
var mydb = this._db;
var shortName = this._shortName;
this.getIndexes().forEach(
function( spec ){
var coll = mydb.getCollection( shortName + ".$" + spec.name );
var mysize = coll.storageSize();
//print( coll + "\t" + mysize + "\t" + tojson( coll.validate() ) );
total += coll.dataSize();
}
);
return total;
}
2009-05-20 20:50:33 +02:00
DBCollection.prototype.convertToCapped = function( bytes ){
if ( ! bytes )
throw "have to specify # of bytes";
return this._dbCommand( { convertToCapped : this._shortName , size : bytes } )
}
2009-05-20 22:43:43 +02:00
DBCollection.prototype.exists = function(){
return this._db.system.namespaces.findOne( { name : this._fullName } );
}
DBCollection.prototype.isCapped = function(){
var e = this.exists();
return ( e && e.options && e.options.capped ) ? true : false;
}
DBCollection.prototype.distinct = function( keyString , query ){
var res = this._dbCommand( { distinct : this._shortName , key : keyString , query : query || {} } );
2009-09-09 23:33:27 +02:00
if ( ! res.ok )
throw "distinct failed: " + tojson( res );
return res.values;
}
DBCollection.prototype.group = function( params ){
params.ns = this._shortName;
return this._db.group( params );
}
2009-05-20 22:43:43 +02:00
DBCollection.prototype.groupcmd = function( params ){
params.ns = this._shortName;
return this._db.groupcmd( params );
}
MapReduceResult = function( db , o ){
Object.extend( this , o );
this._o = o;
this._keys = Object.keySet( o );
this._db = db;
this._coll = this._db.getCollection( this.result );
}
MapReduceResult.prototype._simpleKeys = function(){
return this._o;
}
MapReduceResult.prototype.find = function(){
return DBCollection.prototype.find.apply( this._coll , arguments );
}
MapReduceResult.prototype.drop = function(){
2009-10-23 05:47:52 +02:00
return this._coll.drop();
}
/**
* just for debugging really
*/
MapReduceResult.prototype.convertToSingleObject = function(){
var z = {};
this._coll.find().forEach( function(a){ z[a._id] = a.value; } );
return z;
}
/**
* @param optional object of optional fields;
*/
DBCollection.prototype.mapReduce = function( map , reduce , optional ){
var c = { mapreduce : this._shortName , map : map , reduce : reduce };
if ( optional )
Object.extend( c , optional );
2009-10-23 05:47:52 +02:00
var raw = this._db.runCommand( c );
if ( ! raw.ok )
throw "map reduce failed: " + raw.errmsg;
return new MapReduceResult( this._db , raw );
}
DBCollection.prototype.toString = function(){
return this.getFullName();
}
2009-01-27 04:19:15 +01:00
DBCollection.prototype.toString = function(){
return this.getFullName();
}
DBCollection.prototype.tojson = DBCollection.prototype.toString;
DBCollection.prototype.shellPrint = DBCollection.prototype.toString;