MongoDB Starter Series (4)--mongodb Architecture and client basic operation and attention to detail

Source: Internet
Author: User
Tags findone mongodb client

When it comes to MongoDB's architecture, it is inevitable to compare it with relational databases. Here we take MySQL for example, we make some comparisons:

From the logical structure of the comparison:

MySQL Hierarchy concept MongoDB Hierarchy Concept
Databases (database) Databases (database)
Tables (table) Collection (collection)
Record (ROW) Documents (document)

There is no concept of rows, columns, and relationships in MongoDB, and the document in the collection is equivalent to a record, which embodies the character of freedom of the pattern.

Compare the data storage structure:

Each MySQL database is stored in a folder with the same name as the database, and if MySQL uses the MyISAM storage engine, the database file type includes. frm,. MYD (data stored, D MYI (store index, I is index).

The default data directory for MongoDB is/data/db, which is responsible for storing all mongodb data files. Inside MongoDB, each database contains an. ns file and some data files, and these data files become more and more as the amount of data increases, such as a database called MyDB in the system, then the files that make up the MyDB database will have mydb.ns,mydb.0 , Mydb.1 and so on.

Mydb.ns records the namespace of the database JSON object (namespace abbreviation for NS), which is the namespace within the database collection. mydb.0 and Mydb.1 are the space for objects that hold the database mydb, and the size is incremented by 2 of the n-th size. such as MyDB. ' 0 size is 16M, when the database MyDB storage full 16M, will form a generation mydb.1 continue to store, mydb.1 the size of 32M, and so on, with the increase in data, there will be mydb.2, mydb.3 and other files appear, size 64M, 128M. By default, the current version of MongoDB will pre-allocate a total of 48M space for xxx.0 and xxx.1 when the database is just established, and then generate subsequent xxx.2 as the number of insertions increases.


MongoDB Customer segment Basic operations:

First of all, of course, make sure that MongoDB's Mongod service is open. See my previous blog for details.

Open the MongoDB client's method when running MongoDB's Bin directory under MONGO.

[[email protected] downloads]$ pstree -p | grep mongod            |-mongod (3556)-+-{mongod} (3557)             |               |-{mongod} (3558)            |               |-{mongod} (3559)             |               |-{mongod} (3563)            |               |-{mongod} (3564)             |              &Nbsp;|-{mongod} (3565)            |               |-{mongod} (3566)             |               |-{mongod} (3567)            |                '-{mongod} (3568) [[email  protected] downloads]$ cd /usr/local/mongodb/bin/mongobash: cd: /usr/local/mongodb/ bin/mongo:  is not a directory [[email protected] downloads]$ sudo  /usr/local/mongodb/bin/ mongomongodb shell version: 2.6.8connecting to: testwelcome to the  Mongodb shell. for interactive help, type  "Help". For more comprehensive documentation, seehttp://docs. mongodb.org/questions? try the support grouphttp://groups.google.com/group/mongodb-user 


Here are a few basic operations, along with a detail.

Show DBS means that all databases in MongoDB are displayed. When you have just installed MongoDB, the default is two database admin and local, do not control them.

DB refers to the database in which the current working environment resides. Every time you enter MONGO. The default entry of the database is test, which is an implicitly stored database, if you need to enter a specific database, or to create a new database, only need to "use the database name". In MongoDB do not need to create database this kind of operation, want to use, MongoDB will automatically help us to set up databases, like a thoughtful service "black Deacon." Here, I use DT2 to build a new database DT2, the client immediately real work environment into DT2. However, if you show DBS, the discovery database is not really built. Do you need to create a new table and insert some data? No, you just need to enter any small operations command in the current database DT2, such as showing what the collection of the current database is, and DT2 will be really established.

Connecting to:test> show Dbsadmin (empty) dt1 0.078GBlocal 0.078gb> dbtest> use dt2switched to DB dt2> sh ow dbsadmin (empty) dt1 0.078GBlocal 0.078gb> show collections> show Dbsadmin (empty) dt1 0.078gbdt2 (empt Y) Local 0.078GB

In the above command, show collections is to show which collections are under the current database. Because there is no collection now, so nothing is displayed.

Next we try to set up the collection and insert the data.

> Db.student.find () > Show collections>


MongoDB builds a collection (table), which is still a process that does not need to be declared to establish a table. That is, no operations such as Create collection or create table are required.

You can use it directly.

Here we still first verify a small detail. What the table operation does will cause the table to be generated. Through the above command. We query (find ()) when we haven't student the collection yet, but then the command that displays the collection can see that the student collection has not been established for DT2.

So I inserted a JSON object directly into the student table (the unit stored in MongoDB is a Bson object, which is logically conceptually a document)

> Db.student.insert ({name: "Viper", age:20}) Writeresult ({"ninserted": 1}) > Show Collectionsstudentsystem.indexes>

At this time, when show collections can see, student collection already has. This means that when you create a collection, you must insert valid data into the new collection to actually set up the collection.

The two details above are that when you build a database in MongoDB, the database is created whenever you use the database, and any commands that appear to have no effect under the database, such as a collection of queries, can be set up; A document query for a new collection does not cause the collection to be set up, and a collection of document data must be inserted in order for the collection to be truly established. This is a couple of details that many people may not know!

In addition, when the empty database is set up, an index table is generated, system.indexes. The index values for the Objectid of all the collections under this database are all stored in this area.

Then let's talk about additions and deletions to the following separately.

Increase

The previous example has actually added a document, where we are adding a document to the student collection.

> Db.student.insert ({name: "TA", age:18,phone:["1311234567", "021-87658765"],gpa:{math:88,english:99}}) Writeresult ({"ninserted": 1}) > Db.student.find () {"_id": ObjectId ("54fb0d853fc8173ba3302e6c"), "name": "Viper", "a GE ": {" _id ": ObjectId (" 54fb10493fc8173ba3302e6d ")," name ":" TA "," Age ":" Phone ": [" 1311234567 "," 021-876587 "GPA": {"Math": "English":}>}

As you can see here, I inserted two documents into the student collection of MongoDB, and their "table structure" is not the same. This is one of the most important differences between NoSQL databases and relational databases (other differences mentioned before, ACID properties (transactional support), concurrency).

In the second document we see that the value of Key-value can be a number, string and other basic types, but also can be an array (in fact, can be understood as a stack, the following blog post will describe the value is an array of the case of push and pop, so understood as a stack-like list more properly), Like the phone key above. The more powerful place is that the document, that is, the Keybalue value of the inserted JSON object can be another JSON object, such as the GPA key above.

In fact, these arrays, JSON objects more like the Python syntax in the list and dictionary, haha ...

Here, I'll sort out the value data type of Key-value:

Null A value that represents a null value or nonexistent
Boolean type True and false, such as {male:true}
32-bit integer The MongoDB console uses the JS engine for input, and JS only supports 64-bit floating-point numbers, so 32-bit integers are automatically escaped
64-bit integer As above, will be automatically escaped to 64-bit floating-point number
64-bit floating point number The default type of the console number for MongoDB. such as {salary:23871.12}
String UTF-8 strings can be represented as string types of data
Symbol This type is not supported in MongoDB and will be automatically escaped into a string
ObjectId MongoDB exclusive, Object ID when the unique 12-bit 16 binary ID is in the document. (Timestamp | Machine | PID | Counter
Date Note: When using, add new. such as {birthday:new Date ()}
Regular expressions A document key value can contain a regular expression, and its regular expression is represented by the JS syntax. such as: {key:/ho/i}
Code The document can contain JS documents. such as {key:function () {/*........*/}} (can be an anonymous function without a function name)
Array The value of a key in the document can be represented as an array, and arrays can also be nested within the set.
Embedded documents The document can contain other documents, or it can be embedded as value in the parent document. such as {x:{name: "Happybks", Age:2}}

After inserting the JSON object we can see that the newly inserted each document has been given a _id, which can be understood as a record of the main, is mongodb automatically survive the key, its value is a specific Objectid object, is a 96-bit binary number, by the machine code, Machine process number, time, number of the current namespace four parts automatically generated, unique. Of course, if you want, you can also specify the value of _id when inserting the JSON object, as long as the primary key conflict does not occur, it can be inserted normally.

Adding a record in addition to the Insert method, there is a way to save. Its function is that when you specify the JSON _id, and _id already exists in the collection, it updates the corresponding document; otherwise, a new document is inserted. Take a look at the following example, _ID is a 1 JSON object, the first save is added, and the second is changed.

> db.student.find () {  "_id"  : objectid ("54fb0d853fc8173ba3302e6c"),  "name"  :   "Viper",  "Age"  : 20 }{  "_id"  : objectid ("54fb10493fc8173ba3302e6d"),   "name"  :  "TA",  "Age"  : 18,  "phone"  : [  "1311234567",  " 021-87658765 " ],  GPA"  : {  "Math"  : 88,  "中文版"  : 99  } }> db.student.save ({_id:1,name: "Happybks", age:0}) Writeresult ({  "nmatched"  : 0,   "nupserted"  : 1,  "nmodified"  : 0,  "_id"  : 1 }) >  Db.student.find () {  "_id"  : objectid ("54fb0d853fc8173ba3302e6c"),  "name"  :  "Viper ", " Age " : 20 }{ " _id " : objectid (" 54fb10493fc8173ba3302e6d "), " name "  :  "TA",  "Age"  : 18,  "phone"  : [  "1311234567",  "021-87658765 " ], " GPA" : { " Math " : 88, " Chinese " : 99 } }{ " _id " :  1,  "name"  :  "Happybks",  "Age"  : 0 }> db.student.save ({_id:1, Name: "Hahabks", Age:2}) Writeresult ({  "nmatched"  : 1,  "nupserted"  : 0,  " Nmodified " : 1 }) > db.student.find () { " _id " : objectid (" 54fb0d853fc8173ba3302e6c "), " name " : " Viper ", " Age " : 20 }{ " _id "  : objectid ("54fb10493fc8173ba3302e6d"),  "name"  :  "TA",  "Age"  : 18,   "Phone"  : [  "1311234567",  "021-87658765"  ],  "GPA"  : {  "Math " : 88, " Chinese " : 99 } }{ " _id " : 1, " name " :   "Hahabks",  "Age"  : 2 }>

This article is Oschina blog author's painstaking efforts, reproduced please indicate the source!

This article is Oschina blog author's painstaking efforts, reproduced please indicate the source! (http://my.oschina.net/u/1156339/blog/384073)

Change

The changed operation is using the Update method.

Usage: db.collection.update ({...},{...})

There are two parameters, the first one specifies who to change, and the second one specifies what to change.

But it's not as simple as this, see the example below. The original intention was to add a gender field to the record named Hahabks, but found that all fields except _id were overwritten, leaving only gender. This is obviously not the result of our expectations.

> db.student.find () {  "_id"  : objectid ("54fb0d853fc8173ba3302e6c"),  "name"  :   "Viper",  "Age"  : 20 }{  "_id"  : objectid ("54fb10493fc8173ba3302e6d"),   "name"  :  "TA",  "Age"  : 18,  "phone"  : [  "1311234567",  " 021-87658765 " ],  GPA"  : {  "Math"  : 88,  "中文版"  : 99  } }{  "_id"  : 1,  "name"  :  "Hahabks",  "Age"  : 2 }>  > db.student.update ({name: "Hahabks"},{gender: "Male"}) Writeresult ({  "nmatched"  : 1 ,  "nupserted"  : 0,  "nmodified"  : 1 }) > db.student.find () {  "_id " : objectid (" 54fb0d853fc8173ba3302e6c "), " name " : " Viper ", " Age " : 20  }{  "_id"  : objectid ("54fb10493fc8173ba3302e6d"),  "name"  :  "TA",  "age"  : 18,  " Phone " : [ " 1311234567 ", " 021-87658765 " ],  GPA"  : {  "Math"   : 88,  "中文版"  : 99 } }{  "_id"  : 1,  "gender"  :  " Male " }>

So where does the problem go? Here we need to use an operator $set, specific usage after the article Lee would in detail.

Below I give an example of a workaround, as follows:

> db.student.insert ({name: "TB", Age:11,gender: "Male", "301"}) Writeresult ({  "ninserted"  :  1 }) > db.student.find () {  "_id"  : objectid ("54fb0d853fc8173ba3302e6c"),  "Name"  :  "Viper",  "Age"  : 20 }{  "_id"  : objectid (" 54FB10493FC8173BA3302E6D "), " name " : " TA ", " Age " : 18, " Phone " :  [  "1311234567",  "021-87658765"  ],  "GPA"  : {  "Math"  : 88,  " English " : 99 } }{ " _id " : 1, " gender " : " male " }{   "_id"  : objectid ("54fc521d3fc8173ba3302e6e"),  "name"  :  "TB",  "Age"  :  11,  "gender"  :  "male",  "the" "301"  }> db.student.update ({ Name: "TB"},{$set: {age:22,classid: "1515"}}) Writeresult ({  "nmatched"  : 1,  "nupserted"  :  0,  "Nmodified"  : 1 }) > db.student.find () {  "_id"  : objectid ("54fb0d853fc8173ba3302e6c"),  " Name " : " Viper ", " Age " : 20 }{ " _id " : objectid (" 54FB10493FC8173BA3302E6D "), " name " : " TA ", " Age " : 18, " Phone " :  [  "1311234567",  "021-87658765"  ],  "GPA"  : {  "Math"  : 88,  " English " : 99 } }{ " _id " : 1, " gender " : " male " }{   "_id"  : objectid ("54fc521d3fc8173ba3302e6e"),  "name"  :  "TB",  "Age"  :  22,  "gender"  :  "male",  "the" "301",  "ClassID"  :  "1515"  }>

The above example adds a name called a TB object and then changes it to include changing the original age key value 11 to 22 and adding a new key ClassID assignment "1515". The operator that needs to be used here is $set, which sets the value of the key.

By deleting

The removal method is remove.

Usage is Db.collection.remove ({...})

The parameters specify the conditions of the object you want to delete.

Note that when the parameter is empty, or an empty JSON object. That is db.collection.remove () and db.collection.remove ({}), all documents in the collection will be deleted!!!

> Db.class.insert ({classname: "中文版", Teacher: "Mr A"}) Writeresult ({"ninserted": 1}) > Db.class.insert ({ ClassName: "Math", Teacher: "Mr B"}) Writeresult ({"ninserted": 1}) > Db.class.find () {"_id": ObjectId (" 54fc54773fc8173ba3302e6f ")," classname ":" 中文版 "," Teacher ":" Mr A "} {" _id ": ObjectId (" 54fc54833fc8173ba3302e70 ")," ClassName ":" Math "," Teacher ":" Mr B "}> db.class.remove ({classname:" 中文版 "}) Writeresult ({" nremoved ": 1}) > DB . Class.find () {"_id": ObjectId ("54fc54833fc8173ba3302e70"), "classname": "Math", "Teacher": "Mr B"}> > Db.class. Remove ({}) Writeresult ({"nremoved": 1}) > Db.class.find () >

In the example above, a new class collection is created and two documents are inserted. All of them, see for yourself.

Check

Usage of two

Db.collection.find ({...}), where the parameter is the condition of the query object. If find () or find ({}) is full, this is similar to remove.

Db.collection.findOne ({...}) Similar to find, but it only returns the qualifying object to which the first query is met.

> db.class.insert ({classname: "中文版", Teacher: "Mr aaa"}) Writeresult ({  "ninserted"  :  1 }) > db.class.insert ({classname: "中文版", Teacher: "Mr zzz"}) Writeresult ({  " Ninserted " : 1 }) > db.class.insert ({classname:" 中文版 ", Teacher:" Mr www "}) Writeresult ({  "ninserted"  : 1 }) > db.class.insert ({classname: "中文版", Teacher: "Mr  sss "}) Writeresult ({ " ninserted " : 1 }) > db.class.insert ({classname:" French ", Teacher: "Mr sss"}) Writeresult ({  "ninserted"  : 1 }) > db.class.find ({}) {  " _id " : objectid (" 54fc562e3fc8173ba3302e71 "), " classname " : " 中文版 ", " Teacher "  :  "Mr aaa"  }{  "_id"  : objectid ("54fc56373fc8173ba3302e72"),  " ClassName " : " Chinese ", " teacher " : " mr zzz " }{ " _id " :  ObjectId ("54fc56413fc8173ba3302e73"),   " ClassName " : " Chinese ", " teacher " : " mr www " }{ " _id " :  ObjectId ("54fc564e3fc8173ba3302e74"),  "classname"  :  "中文版",  "Teacher"  :  "Mr  sss " }{ " _id " : objectid (" 54fc56603fc8173ba3302e75 "), " classname " : " French ", " Teacher " : " Mr sss " }> db.class.findone ({classname:" 中文版 "}) {" _id " : objectid (" 54fc562e3fc8173ba3302e71 ")," classname " : " 中文版 "," Teacher " : " Mr  aaa "}> db.class.find ({classname:" 中文版 "}) { " _id " : objectid (" 54fc562e3fc8173ba3302e71 "), " classname " : " 中文版 ", " Teacher " : " MR AAA "  }{  "_id"  : objectid ("54fc56373fc8173ba3302e72"),  "classname"  :  "中文版",   "Teacher"  :  "mr zzz"  }{  "_id"  : objectid ("54fc56413fc8173ba3302e73"),   "classname"  :  "ENglish ", " Teacher " : " mr www " }{ " _id " : objectid (" 54fc564e3fc8173ba3302e74 "), " classname " : " 中文版 ", " Teacher " : " Mr sss "  }>

See the example above for yourself.

This article first wrote here, add and remove changes to check the contents of a lot of things, I will put in the back of the article write, haha!




MongoDB Starter Series (4)--mongodb Architecture and client basic operation and attention to detail

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.