`
leonzhx
  • 浏览: 768145 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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));
}
 

 

分享到:
评论

相关推荐

    MongoDB in Action

    MongoDB through the JavaScript shell Writing programs using MongoDB PART 2 APPLICATION DEVELOPMENT IN MONGODB Document-oriented data Queries and aggregation Updates, atomic operations, and deletes...

    MongoDB(mongodb-org-shell-5.0.4-1.el7.x86_64.rpm)

    MongoDB Community Server(mongodb-org-shell-5.0.4-1.el7.x86_64.rpm)适用于RedHat / CentOS 7.0 MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。 ...

    MongoDB(mongodb-org-shell_5.0.4_amd64.deb)

    MongoDB Community Server(mongodb-org-shell_5.0.4_amd64.deb)适用于适用于Debian10 MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。 MongoDB是一...

    MongoDB(mongodb-org-shell-5.0.4-1.suse15.x86_64.rpm)

    MongoDB Community Server(mongodb-org-shell-5.0.4-1.suse15.x86_64.rpm)适用于SUSE15 MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。 MongoDB是...

    MongoDB(mongodb-org-shell-5.0.4-1.suse12.x86_64.rpm)

    MongoDB Community Server(mongodb-org-shell-5.0.4-1.suse12.x86_64.rpm)适用于SUSE12 MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。 MongoDB是...

    MongoDB(mongodb-shell-linux-x86_64-rhel70-5.0.4.tgz)

    MongoDB Community Server(mongodb-shell-linux-x86_64-rhel70-5.0.4.tgz)适用于RedHat / CentOS 7.0 MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案...

    MongoDB(mongodb-shell-linux-x86_64-suse12-5.0.4.tgz)

    MongoDB Community Server(mongodb-shell-linux-x86_64-suse12-5.0.4.tgz)适用于SUSE12 MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。 MongoDB是...

    MongoDB(mongodb-shell-linux-x86_64-suse15-5.0.4.tgz)

    MongoDB Community Server(mongodb-shell-linux-x86_64-suse15-5.0.4.tgz)适用于SUSE15 MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。 MongoDB是...

    《MongoDB实战》第2版-第2章-JavaScript命令操作Mongodb1

    第 2 章通过JavaScript shell操作MongoDBMongoDB through the JavaScript shell本章内容MongoDB

    MongoDB客户端访问(Shell方式 ) .pdf

    MongoDB客户端访问(Shell方式 ) .pdf 学习资料 复习资料 教学资源

    dump-mongodb.sh(备份MongoDB数据库shell)

    Mongodb备份数据库的shell脚本文件, 经过在实际项目中测试使用过.

    webmongo1.0

    You can do almost invoke on mongodb through the javascript API in browser. 客户端的JavaScript API支持` IE6.0 +浏览器Firefox和微信(译者注:小程序和公众号)` The client javascript api support `IE6.0+ ...

    mongodb 4.4.19

    包含 mongodb-org-4.4.19-1.el7.x86_64.rpm ...mongodb-org-shell-4.4.19-1.el7.x86_64.rpm mongodb-org-tools-4.4.19-1.el7.x86_64.rpm mongod.conf 不需要用户密码的配置 mongod.conf.auth 需用户密码的配置

    JavaScript Applications with Node.js, React, React Native and MongoDB

    JavaScript Applications with Node.js, React, React Native and MongoDB: Design, code, test, deploy and manage in Amazon AWS By 作者: Eric Bush ISBN-10 书号: 0997196661 ISBN-13 书号: 9780997196665 出版...

    MongoDB The Definitive Guide

    How does MongoDB help you manage a huMONGOus amount of data collected through your web application? With this authoritative introduction, you’ll learn the many advantages of using document-oriented ...

    MongoDB(mongodb-shell-linux-x86_64-debian10-5.0.4.tgz)

    MongoDB Community Server(mongodb-shell-linux-x86_64-debian10-5.0.4.tgz)适用于Debian10 MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。 ...

    MongoDB The Definitive Guide 2011 中文+英文

    MongoDB: The Definitive Guide by Kristina Chodorow and Michael Dirolf Copyright © 2010 Kristina Chodorow and Michael Dirolf. All rights reserved.

    MongoDB The Definitive Guide 3rd Edition

    Written by current and former members of the MongoDB team, the third edition is updated for MongoDB 4.0. You’ll find substantial updates on querying, indexing, aggregation, replica sets, ops manager,...

    MongoDB权威指南:MongoDB:The Definitive Guide

    MongoDB权威指南:MongoDB:The Definitive Guide第一版 第二版 中、英文4本合集

    docker-mongodb-shell:在Docker容器中安装mongo shell和工具的示例

    mongodb-org-shell ,包含mongo shell。 mongodb-org-tools ,包含以下MongoDB工具:mongoimport bsondump,mongodump,mongoexport,mongofiles,mongorestore,mongostat和mongotop。 docker build --rm -t ...

Global site tag (gtag.js) - Google Analytics