Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the basic operations and details of Mongodb architecture and client?

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article shows you the Mongodb architecture and client basic operation and pay attention to the details, the content is concise and easy to understand, absolutely can make your eyes bright, through the detailed introduction of this article, I hope you can get something.

When it comes to the architecture of Mongodb, it is inevitable to make a comparison with relational databases. Taking MySQL as an example, let's make some comparisons:

In terms of logical structure:

MySQL hierarchy concept MongoDB hierarchy concept

Database (database) Database (database)

Table (table) collection (collection)

Record (row) document (document)

There is no concept of row, column or relationship in MongoDB, and the document in the collection is equivalent to a record, which reflects the characteristic of schema freedom.

Compare in terms of data storage structure:

Each database of MySQL is stored in a folder with the same name as the database. If MySQL uses the MyISAM storage engine, the database file types include .frm, .MYD (storing data, D is Data), and .MYI (storing index, I is Index).

The default data directory for MongoDB is / data/db, which is responsible for storing all MongoDB data files. Within MongoDB, each database contains A. ns file and some data files, and these data files will become more and more with the increase of the amount of data, for example, if there is a database called mydb in the system, then the files that make up the database mydb will be composed of mydb.ns,mydb.0,mydb.1 and so on.

Mydb.ns records the namespace of database Json objects (ns is the abbreviation for namespace), that is, the namespace in the database collection. Mydb.0 and mydb.1 are the spaces where objects in the database mydb are stored, and the size is incremented to the nth power of 2. For example, if the size of mydb.`0 is 16m, when the database mydb is full of 16m, it will form a generated mydb.1 to continue storage, and the size of mydb.1 is 32m. And so on, with the increase of data, there will be files such as mydb.2, mydb.3, etc., with a size of 64m and 128m. By default, the current version of Mongodb pre-allocates 48m of XXX.0 and XXX.1 space when the database is established, and then generates subsequent xxx.2 as the number of inserts increases.

Basic operation of MongoDB client segment:

The first step, of course, is to make sure that MongoDB's mongod service is turned on. See my previous blog for details.

Run mongo under MongoDB's bin directory when you open the method of the MongoDB client.

[neil@neilhost Downloads] $pstree-p | grep mongod |-mongod (3556)-+-{mongod} (3557) | |-{mongod} (3558) | |-{mongod} (3559) | |-{mongod} (3563) | |-{mongod} (3564) |-{mongod} (3565) | |-{mongod} (3566) |-{mongod} (3567) | `- {mongod} (3568) [neil@neilhost Downloads] $cd / usr/local/mongodb/bin/mongo bash : cd: / usr/local/mongodb/bin/mongo: not a directory [neil@neilhost Downloads] $sudo / usr/local/mongodb/bin/mongo MongoDB shell version: 2.6.8 connecting to: test Welcome to the MongoDB shell. For interactive help, type "help". For more comprehensive documentation, see http://docs.mongodb.org/ Questions? Try the support group http://groups.google.com/group/mongodb-user

Next, I'll introduce a few basic operations, as well as a detail.

Show dbs means to display all the databases in the mongodb. When mongodb is first installed, there are two databases, admin and local, by default, leaving them alone.

Db refers to the database in which the current work environment resides. Every time you enter mongo. The default database to enter is test, which is an implicitly stored database. If you need to enter a specific database, or if you want to set up a new database, you only need a "use database name". There is no need for create database in mongodb. You can use it if you want. Mongodb will automatically set up a database for us, just like a well-served "black deacon". Here, I use dt2 set up a new database, dt2, and the client immediately transfers the real work environment to dt2. However, if you show dbs, you will find that the 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 operation command in the current database dt2, such as showing what the collection of the current database is, and the dt2 will be really created.

Connecting to: test > show dbs admin (empty) dt1 0.078GB local 0.078GB > db test > use dt2 switched to db dt2 > show dbs admin (empty) dt1 0.078GB local 0.078GB > show collections > show dbs admin (empty) dt1 0.078GB dt2 (empty) local 0.078GB

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

Next we try to create a collection and insert data.

> db.student.find () > show collections >

Mongodb creating collections (tables) is still a process that does not need to declare the creation of tables. That is, no operations such as create collection or create table are required.

Just use it.

Here we still verify a small detail first. What kind of table operation will lead to table generation. Through the above command. We query the student collection when it is not yet available (find ()), but the command that displays the collection later can see that no student collection has been created for dt2.

So I insert a Json object directly into the student table (the unit stored in Mongodb is the Bson object, which is logically a document)

> db.student.insert ({name: "Viper", age:20}) WriteResult ({"nInserted": 1}) > show collections student system.indexes >

At this point, when you show collections, you can see that the student collection already exists. This means that when creating a collection, you must insert valid data into the new collection in order to really create the collection.

To sum up the two details above is that when establishing a database in MongoDB, as long as you use the database, and execute any commands under the database that do not seem to have any impact, such as querying the collection, it will make the database set up; however, if you are in the database, the document query for the new collection will not lead to the establishment of the collection, there must be document data inserted into the collection in order to make the collection really established. Many people may not know such a pair of details!

In addition, when an empty database builds a collection, an index table, system.indexes, is generated. The index values of the ObjectId of all collections under the database are stored here.

Well, next, let's talk about additions, deletions, changes and searches respectively.

Increase

A document has actually been added to the previous example, and here 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", "age": 20} {"_ id": ObjectId ("54fb10493fc8173ba3302e6d"), "name": "TA" "age": 18, "phone": ["1311234567", "021-87658765"], "GPA": {"Math": 88, "English": 99}} >

Here you can see that the "table structures" of the two documents I inserted into the student collection of mongodb are different. This is one of the most important differences between NoSQL databases and relational databases (other differences have been mentioned earlier, ACID features (transaction support), concurrency).

In the second document, we see that the value of key-value can be an array in addition to some basic types such as numbers, strings, etc. (in fact, it can be understood as a stack, the later blog article will introduce that value is an array of push and pop, so it is more appropriate to understand it as a list similar to the stack), such as the phone key above. More powerful is that the value of the keybalue of the inserted Json object can be another Json object, such as the GPA key above.

In fact, these arrays and json objects are more like lists and dictionaries in python syntax.

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

Null: indicates a null or nonexistent value

Boolean types: true and false, such as {male:true}

32-bit integers: Mongodb's console uses the JS engine for input, while JS only supports 64-bit floating-point numbers, so 32-bit integers are automatically escaped

64-bit integer: the same as above, will be automatically escaped to 64-bit floating-point number

64-bit floating point number: the default type of console digits for Mongodb. Such as {salary:23871.12}

Strings: UTF-8 strings can be represented as data of string type

Symbols: this type is not supported in MongoDB and will be automatically escaped to a string

ObjectId: unique to MongoDB, the object id is the 12-bit hexadecimal id in the document. (timestamp | Machine | PID | counter)

Date: note: add new when you use it. Such as {birthday:new Date ()}

Regular expressions: document keys can contain regular expressions, which are represented by JS syntax. For example: {key:/ho/i}

Code: a document can contain an JS document. For example, {key:function () {/ *. * /}} (can be an anonymous function without a function name)

Array: the value of the key in the document can be represented as an array, and arrays can be nested within the array.

Embedded documents: documents can contain other documents or can be embedded in the parent document as a value. For example, {x: {name: "happyBKs", age:2}}

After inserting the Json object, we can see that each newly inserted document is assigned a _ id, which can be understood as the master of the record. It is the key automatically generated by mongodb. Its value is a specific ObjectId object, a 96-bit binary number, and is automatically generated by machine code, machine process number, time, and the current namespace number. Of course, if you like, you can also specify the value of _ id when inserting the Json object, which can be inserted normally as long as there is no primary key conflict.

There is another way to add a record in addition to the insert method, and that is save. Its function is that when you specify the _ id of Json, and _ id already exists in the collection, then it will update the corresponding document; otherwise, insert a new document. Take a look at the following example, where the Json object of _ id is 1, the * save is added and the second time it 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 "English": 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, "English": 99}} {"_ id": 1, "name": "happyBKs", "age": 0} > db.student.save ({_ id:1,name: "BKs", 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, "English": 99}} {"_ id": 1, "name": "BKs", "age": 2} >

Change

The operation of the change uses the update method.

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

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

But it's not that simple. Take a look at the example below. The original plan was to add a gender field to the record named BKs, but found that all the fields except _ id were overwritten, leaving only gender. This is obviously not what we expected.

> 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, "name": "BKs", "age": 2} > > db.student.update ({name: "BKs"}, {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, "English": 99}} {"_ id": 1, "gender": "male"} >

So what's the problem? Here we need to use an operator $set, the specific usage of which will be described in more detail in later articles.

Let me give you an example of a solution directly, as follows:

> db.student.insert ({name: "TB", age:11,gender: "male", room: "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" "room": "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", "room": "301", "classid": "1515"} >

The above example is to add an object called name TB, and then make changes to it, including changing the value of the original age key 11 to 22, and adding a new key classid assignment "1515". The operator you need to use here is $set, which is used to set the value of the key.

Delete

The method to delete is remove.

The usage is db.collection.remove ({...})

The parameter specifies the condition of the object you want to delete.

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

> db.class.insert ({classname: "English", teacher: "Mr A"}) WriteResult ({"nInserted": 1}) > db.class.insert ({classname: "Math", teacher: "Mr B"}) WriteResult ({"nInserted": 1}) > db.class.find () {"_ id": ObjectId ("54fc54773fc8173ba3302e6f"), "classname": "English", "teacher": "Mr A"} {"_ id": ObjectId ("54fc54833fc8173ba3302e70") "classname": "Math", "teacher": "Mr B"} > db.class.remove ({classname: "English"}) 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 above example, a new class collection is created and two documents are inserted. See for yourself all of them.

Check

There are two uses.

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

Db.collection.findOne ({...}) is similar to find, but it only returns * eligible objects that have been queried.

> db.class.insert ({classname: "English", teacher: "Mr AAA"})

WriteResult ({"nInserted": 1})

> db.class.insert ({classname: "English", teacher: "Mr ZZZ"})

WriteResult ({"nInserted": 1})

> db.class.insert ({classname: "English", teacher: "Mr WWW"})

WriteResult ({"nInserted": 1})

> db.class.insert ({classname: "English", teacher: "Mr SSS"})

WriteResult ({"nInserted": 1})

> db.class.insert ({classname: "French", teacher: "Mr SSS"})

WriteResult ({"nInserted": 1})

> db.class.find ({})

{"_ id": ObjectId ("54fc562e3fc8173ba3302e71"), "classname": "English", "teacher": "Mr AAA"}

{"_ id": ObjectId ("54fc56373fc8173ba3302e72"), "classname": "English", "teacher": "Mr ZZZ"}

{"_ id": ObjectId ("54fc56413fc8173ba3302e73"), "classname": "English", "teacher": "Mr WWW"}

{"_ id": ObjectId ("54fc564e3fc8173ba3302e74"), "classname": "English", "teacher": "Mr SSS"}

{"_ id": ObjectId ("54fc56603fc8173ba3302e75"), "classname": "French", "teacher": "Mr SSS"}

> db.class.findOne ({classname: "English"})

{

"_ id": ObjectId ("54fc562e3fc8173ba3302e71")

"classname": "English"

"teacher": "Mr AAA"

}

> db.class.find ({classname: "English"})

{"_ id": ObjectId ("54fc562e3fc8173ba3302e71"), "classname": "English", "teacher": "Mr AAA"}

{"_ id": ObjectId ("54fc56373fc8173ba3302e72"), "classname": "English", "teacher": "Mr ZZZ"}

{"_ id": ObjectId ("54fc56413fc8173ba3302e73"), "classname": "English", "teacher": "Mr WWW"}

{"_ id": ObjectId ("54fc564e3fc8173ba3302e74"), "classname": "English", "teacher": "Mr SSS"}

>

What are the above contents of Mongodb architecture and client basic operation and attention details? have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report