MongoDB Common operations

Source: Internet
Author: User
Tags mongodb mongo shell

MongoDB Common Operations


First, we start MongoDB:

[Root@h3/]# mongod-f/etc/mongod.conf Wed June 23:38:58.195 Wed June 23:38:58.195 warning:32-bit do
N ' t have journaling enabled by default. Please use the--journal if you want durability.
Wed June 23:38:58.195 about
to fork the child process, waiting until server was ready for connections.
Forked process:14093 all
output going to:/var/log/mongo/mongod.log child
Process started successfully, parent E Xiting
[Root@h3/]#

Then we go into the MONGO shell:

[Root@h3/]# MONGO
MongoDB shell version:2.4.5 connecting to:test
Server has startup warnings:
Wed June 2 4 23:38:58.244 [Initandlisten]
Wed 23:38:58.244 [initandlisten] * * Note:this is a bit MongoDB binary.
Wed June 23:38:58.244 [Initandlisten] * *       bit builds are limited to less than 2GB of data (or less with--journal) .
Wed June 23:38:58.244 [Initandlisten] * * * This journaling defaults to off for bit and are       currently off.
Wed June 23:38:58.244 [Initandlisten] * *       http://dochub.mongodb.org/core/32bit
Wed June 24 23:38:58.244 [ Initandlisten]
>
Here, briefly describe the functions of the following MONGO shell:

1, with full-featured JavaScript interpreter;

2, you can complete any JavaScript commands;

3, you can complete the MONGODB operations management commands with a strong JavaScript style.


For example, we perform JavaScript operations in the shell:

> var x = m;
> X/3
> x + 33.333333333333336
> x-40
>

A little more powerful:

> Math.sin (MATH.PI/2)
1
> function FAC (n) {
... if (n <= 1) {...   return 1;
... }
... return n * FAC (N-1);
... }
> FAC (5);
>

To switch databases in MongoDB:

> Use foobar
switched to DB foobar
> Use xyz
switched to DB xyz
> DB
xyz
>


New records are added to the MongoDB.

When you insert a record, MongoDB checks to see if the document contains _id, and if the document does not contain _ID,MONGODB, it is created for it.

> Use blog
switched to DB blog
> post = {' title ': ' I blog post ', ' content ': ' Here's my blog post. ', ' date ': New Date ()}
{
        "title": "My blog post",
        "content": "This is the My blog post.",
        "Date": Isodate ("2013-07-2 4t17:15:29.168z ")
}
> Db.blog.insert (POST)
> Db.blog.find ()
{" _id ": ObjectId (" 51f00bbecd26ce7df43a2e86 ")," title ":" My blog post "," Content ":" This is the My blog post. "," date ": Isodate (" 2013-07-24t17 : 15:29.168z ")}
>

Here, a little bit: "_id" for the system by default added to the field, used to uniquely identify the document, similar to the Rowid,objectid in Oracle is the default generation of IDs, consisting of 12 bytes (24 16 binary digits), the 第0-3 byte is a timestamp, The 4–6 byte is the machine identifier (typically the hash value of the host name), and the 第7-8 byte is the pid,9-11 byte as the counter.


Read data:

> Db.blog.findOne ()
{
        "_id": ObjectId ("51f00bbecd26ce7df43a2e86"),
        "title": "My Blog Post",
        "Content": "Here's my blog post.",
        "date": Isodate ("2013-07-24t17:15:29.168z")
}
>

Modify Data:

> post.comments = []
[]
> Db.blog.update ({title: ' My blog post '}, post)
> Db.blog.find ()
{"_id ": ObjectId (" 51f00bbecd26ce7df43a2e86 ")," title ":" My blog post "," Content ":" This is the My blog post. "," date ": Isodate ( "2013-07-24t17:15:29.168z"), "comments": []}
>

Delete data:

> Db.blog.remove ({title: ' My Blog Post '})
> Db.blog.find ()
>

Ask for help:

> Help Db.help () Help on DB Methods Db.mycoll.help () Help on Collection
        Methods Sh.help () sharding helpers rs.help () replica set helpers
        Help Admin administrative help connect connecting to a DB help                      Help keys key shortcuts help Misc misc Things to know help Mr MapReduce Show DBS Show database names show collections S How to collections in the current database show the users in the current database show ProFi Le show most recent system.profile entries with time >= 1ms show logs show t He accessible logger names show log [name] prints out the last segment of log in memory, ' global ' is Default Use <Db_name> Set Current database Db.foo.find () list objects in collection Foo Db.foo.find ({a:1}) List objects in Foo where a = = 1 It result of the last Li NE evaluated;                         Use to further iterate dbquery.shellbatchsize = X Set default number of items to display on shell exit
 Quit the MONGO shell >


View function Source:

> Db.blog.insert
function (obj, options, _allow_dot) {
    if (! obj)
        Throw "no object passed to insert!";
    if (! _allow_dot) {
        this._validateforstorage (obj);
    }

    if (typeof (options) = = "undefined") options = 0;

    if (typeof (obj._id) = = "Undefined" &&! Array.isarray (obj)) {
        var tmp = obj;//don ' t want to modify input
        obj = {_id:new ObjectId ()};
        for (var key in tmp) {
            Obj[key] = Tmp[key];
        }
    }
    var starttime = (typeof (_verboseshell) = = ' undefined ' | |
                     ! _verboseshell)? 0:new Date (). GetTime ();
    This._mongo.insert (This._fullname, obj, options);
    This._lastid = obj._id;
    This._printextrainfo ("Inserted", starttime);
}
>


MongoDB after an abnormal shutdown, the following error occurs during startup:

[Root@h3 ~]# mongod-f/etc/mongod.conf Wed June 23:25:10.802 Wed June 23:25:10.802 warning:32-bit do
N ' t have journaling enabled by default. Please use the--journal if you want durability.
Wed June 23:25:10.802 about
to fork the child process, waiting until server was ready for connections.
Forked process:14043 all
output going to:/var/log/mongo/mongod.log
error:child process failed, exited with Erro R number
[Root@h3 ~]#
The reason is that MongoDB is locked in MONGO's path directory (my directory is/var/lib/mongo/) will be mongod.lock deleted, and then run the command: Mongod-repair repair MongoDB, and then start.

Ps:

The normal way to close MongoDB is:

Enter the MONGO shell and run the following command:

> Use admin
switched to DB admin
> Db.shutdownserver ()
Wed 23:41:42.497 dbclientcursor::init cal L () failed
server should is down ...
Wed June 23:41:42.536 trying reconnect to 127.0.0.1:27017 Wed June
23:41:42.539 reconnect 127.0.0.1:27017 C Ouldn ' t connect to server 127.0.0.1:27017
>



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.