MongoDB through the JavaScript shell

1.  If no other database is specified on startup, the shell selects a default database called test . creating the database isn’t required. You can see the db to which you are connecting by typing db . Just use use <dbname> to switch to the target database. Databases and collections are created only when documents are first inserted. If you’re concerned about databases or collections being created accidentally, most of the drivers let you enable a strict mode to prevent such careless errors.


2.  To create a document under users collection (in current database), you use :

>db.users.insert({username: "smith"})
 

If the insert succeeds, then you’ve just saved your document. You can issue a simple query to verify that the document has been saved:

>db.users.find()
 

The response will look like:

{ _id : ObjectId("4bf9bec50e32f82523389314"), username : "smith" }
 

You can think of the _id value as the document’s primary key. Every MongoDB document requires an _id , and if one isn’t present when the document is created, then a special MongoDB object ID will be generated and added to the document at that time. It will be unique among all _id values in the collection

3.  If the shell does not accept the collection name (for example if it starts with a number, contains a space etc), use:

>db['foo'].find()

4.  You can find the number of the documents by :

>db.users.count()
 


5.  You can pass a simple query selector to the find method. A query selector is a document that’s used to match against all documents in the collection. To query for all documents where the username is jones , you pass a simple document that acts as your query selector:

>db.users.find({username: "jones"})
 


6.  All updates require at least two arguments. The first specifies which documents to update, and the second defines how the selected documents should be modified. Suppose that user smith decides to add her country of residence. You can record this with the following update:

>db.users.update({username: "smith"}, {$set: {country: "Canada"}})
 

If the user later decides that she no longer wants her country stored in her profile, she can remove the value using the $unset operator:

>db.users.update({username: "smith"}, {$unset: {country: 1}})
 


7.  Given the document like:

{ username: "smith",
  favorites: {
    cities: ["Chicago", "Cheyenne"],
    movies: ["Casablanca", "For a Few Dollars More", "The Sting"]
  }
}
 

You can find all users who like the movie Casablanca by:

>db.users.find({"favorites.movies": "Casablanca"})
 


8.  If you want to add an element to the list, you’re better off using either $push or $addToSet . Both operators add an item to an array, but the second does so uniquely, preventing a duplicate addition. If any user who likes Casablanca also like The Maltese Falcon , you can update your database to reflect this fact:

>db.users.update( {"favorites.movies": "Casablanca"},
    {$addToSet: {"favorites.movies": "The Maltese Falcon"} },
          false,
          true )
 

The fourth argument, true , indicates that this is a multi-update. By default, a MongoDB update operation will apply only to the first document matched by the query selector. If you want the operation to apply to all documents matched, then you must be explicit about that.


9.  If given no parameters, a remove operation will clear a collection of all its documents:

>db.users.remove()
 

If you want to remove all users whose favorite city is Cheyenne , you can:

>db.users.remove({"favorites.cities": "Cheyenne"})
 

10.  If your intent is to delete the collection along with all of its indexes, use the drop() method:

>db.users.drop()
 


11.  All queries create a cursor, which allows for iteration over a result set. If we haven't assigned that cursor to a variable, the shell automatically iterates over the cursor. If there are too many results for the query, the shell will only show first 20 documents of them(first result set), to show the next result set, you use it . By setting the shellBatchSize you can change this: 

>DBQuery.shellBatchSize = #
 

12.  We can explicitly use the cursor returned from the find() operation:

> var cursor = db.things.find();
> while (cursor.hasNext()) printjson(cursor.next());
 

The hasNext() function tells if there are any more documents to return, and the next() function returns the next document. We also used the built-in printjson() method to render the document in a pretty JSON-style format.

13.  We can also use the functional features of the Javascript language, and just call forEach on the cursor:

> db.things.find().forEach(printjson);
 

In the case of a forEach() we must define a function that is called for each document in the cursor.

14.  You can also treat cursors like an array :

> var cursor = db.things.find();
> printjson(cursor[4]);
 

When using a cursor this way, note that all values up to the highest accessed (cursor[4] above) are loaded into RAM at the same time. This is inappropriate for large result sets, as you will run out of memory. Cursors should be used as an iterator with any query which returns a large number of elements. In addition to array-style access to a cursor, you may also convert the cursor to a true array:

> var arr = db.things.find().toArray();
 

These array features are specific to mongo - The Interactive Shell, and not offered by all drivers.

15.  MongoDB cursors are not snapshots - operations performed by you or other users on the collection being queried between the first and last call to next() of your cursor may or may not be returned by the cursor. Use explicit locking to perform a snapshotted query.

16.  You may limit the size of a query's result set by specifing a maximum number of results to be returned via the limit() method.

> db.things.find().limit(3);
 

17.  findOne() takes all the same parameters of the find() function, but instead of returning a cursor, it will return either the first document returned from the database, or null if no document is found that matches the specified query. It’s the equivalent of find({name:"mongo"}).limit(1) .


18.  You can also issue range queries using the special $gt and $lt operators: (They stand for greater than and less than, respectively.)

>db.numbers.find( {num: {"$gt": 20, "$lt": 25 }} )
 

19.  The query expression is an document itself. A query document of the form { a:A, b:B, ... } means "where a==A and b==B and ...".

20.  MongoDB also lets you return "partial documents" - documents that have only a subset of the elements of the document stored in the database. To do this, you add a second argument to the find() query, supplying a document that lists the elements to be returned:

> db.things.find({x:4}, {j:true}).forEach(printjson);
 

This query will only have the attribute “j ” and “_id ”(which is always returned) in the result document.


21.  SQL’s EXPLAIN describes query paths and allows developers to diagnose slow operations by determining which indexes a query has used. MongoDB has its own version of EXPLAIN that provides the same service:

>db.numbers.find( {num: {"$gt": 199995 }} ).explain()
 

The result should look:

{
  "cursor" : "BasicCursor",
  "nscanned" : 200000,
  "nscannedObjects" : 200000,
  "n" : 4,
  "millis" : 171,
  "nYields" : 0,
  "nChunkSkips" : 0,
  "isMultiKey" : false,
  "indexOnly" : false,
  "indexBounds" : { }
}
 

nscanned ” means how many documents this query has scanned. And “n ” means the number of documents returned by the query. The BasicCursor cursor type verifies that this query hasn’t used an index to return the result set.

22.  You can create an index for the num key using the ensureIndex() method:

>db.numbers.ensureIndex({num: 1})
 

The {num: 1} indicates that an ascending index should be built on the num key for all documents in the numbers collection. The index created can be verified by:

>db.numbers.getIndexes()
[
  {
    "name" : "_id_",
    "ns" : "tutorial.numbers",
    "key" : {
      "_id" : 1
    }
  },

  {
    "_id" : ObjectId("4bfc646b2f95a56b5581efd3"),
    "ns" : "tutorial.numbers",
    "key" : {
      "num" : 1
    },
    "name" : "num_1"
  }
]

The first is the standard _id index that’s automatically built for every collection; the second is the index created on num .


23.  To get all fields that have indexes on them:

>db.foo.getIndexKeys()
 


24.  show dbs prints a list of all the databases on the system. show collections (or show tables ) displays a list of all the collections defined on the current database. system.indexes is a special collection that exists for every database. Each entry in system.indexes defines an index for the database. You can query this collection directly, but its output is more easily viewed using the getIndexes() method.

25.  When run stats() on a database object, you’ll get the following output:

>db.stats()
{
  "collections" : 4,
  "objects" : 200012,
  "dataSize" : 7200832,
  "storageSize" : 21258496,
  "numExtents" : 11,
  "indexes" : 3,
  "indexSize" : 27992064,
  "ok" : 1
}
 

You can also run the stats() command on an individual collection:

>db.numbers.stats()
{
  "ns" : "tutorial.numbers",
  "count" : 200000,
  "size" : 7200000,
  "storageSize" : 21250304,
  "numExtents" : 8,
  "nindexes" : 2,
  "lastExtentSize" : 10066176,
  "paddingFactor" : 1,
  "flags" : 1,
  "totalIndexSize" : 27983872,
  "indexSizes" : {
    "_id_" : 21307392,
    "num_1" : 6676480
 },
  "ok" : 1
}
 


26.  A certain set of MongoDB operations—distinct from the insert, update, delete, and query operations are known as database commands. Database commands are generally administrative but they may also control core MongoDB features, such as map-reduce. What all database commands have in common is their implementation as queries on a special virtual collection called $cmd .

27.  db.runCommand( {dbstats: 1} ) are identical to the db.stats() method. You can run any available command by passing its document definition to the runCommand method. For db.numbers.stats() , its corresponding command is db.runCommand( {collstats: 'numbers'} )

28.  The MongoDB shell will print the implementation of any method whose executing parentheses are omitted:

>db.runCommand
  function (obj) {
    if (typeof obj == "string") {
      var n = {};
      n[obj] = 1;
      obj = n;
    }
    return this.getCollection("$cmd").findOne(obj);
  }
 

The last line in the function is nothing more than a query on the $cmd collection.

29.  A database command is a query on a special collection, $cmd , where the query selector defines the command itself. To run the collection stats command manually, you can :
>db.$cmd.findOne( {collstats: 'numbers'} );

30.  db.help() prints a list of commonly used methods for operating on database objects. You’ll find a similar list of methods for operating on collections by running db.foo.help() .

31.  There’s also built-in tab completion. Start typing the first characters of any method and then press the Tab key twice. You’ll see a list of all matching methods.


32.  save() is merely a wrapper for insert() and update() . If the object you’re trying to save doesn’t have an _id field, then the field is added, and insert() is invoked; otherwise, an update is performed.

33.  If you are curious about what a function is doing, you can type it without the () s and the shell will print the source:

> printjson
function (x) {
    print(tojson(x));
}
 

猜你喜欢

转载自seanzhou.iteye.com/blog/1572597