Getting started with MongoDB (2): basic concepts and data types of MongoDB

Source: Internet
Author: User
Tags mongodb client mongodb server
In the previous article, we talked about MongoDB installation and management, which involves some concepts, data structures, and some API calls. It doesn't matter if you don't know it. It's actually very simple. This article will briefly introduce it. 1. Document is the core concept of MongoDB. Multiple key-value pairs are put together in an orderly manner. Document is the most basic data structure for MongoDB to store data.

In the previous article, we talked about MongoDB installation and management, which involves some concepts, data structures, and some API calls. It doesn't matter if you don't know it. It's actually very simple. This article will briefly introduce it. 1. Document is the core concept of MongoDB. Multiple key-value pairs are put together in an orderly manner. Document is the most basic data structure for MongoDB to store data.

In the previous article, we talked about MongoDB installation and management, which involves some concepts, data structures, and some API calls. It doesn't matter if you don't know it. It's actually very simple. This article will briefly introduce it.

1. Documentation

A document is the core concept of MongoDB, and multiple key-value pairs are put together in an orderly manner. A document is the most basic data structure for MongoDB to store data. MongoDB is operated in the form of documents. a json-like binary BSON data format is used, and API calls are all passed document parameters. Each programming language has a data structure that identifies documents, such as java map, lua table, and python dict, but they are all similar. A key corresponds to a value. Compared with MySQL, The MongoDB document is equivalent to a row of data in the MySQL table.

Statement 1> db. people. insert ({"name": "Mary", "age": 10}) method 2> person1 = {"name": "Mary", "age ": 10}> db. people. insert (person1)

The above two statements are the same. They all insert a document into the people set of the database. The second method uses the variable person1 to indicate the document to be inserted.

The key-value pairs in the document are ordered. The following two documents are different:

doc1 = {"name" : "Mary", "age" : 10}doc2 = {"age" : 10, "name" : "Mary"}

The key of the document must be of the string type, but the value can be of many types, which will be discussed later. The document is case sensitive. The name and Name keys are different. The keys in the document must be unique.

2. Set

As mentioned above, the set of people is equivalent to a table in MySQL. MongoDB lists all the sets either show tables or show collections. A collection is a set of documents and has no pattern. documents in a collection can be of various types:

db.people.insert({"name" : "Mary", "age" : 10})db.people.insert({"country" : "USA", "languge" : "english"})

For example, two documents are inserted to the people set above, but these two documents are completely different and their keys are different. In this case, not all documents can be placed in one set, this is true, but this is indeed a problem. When the set is large to a certain extent, the speed will become very slow, and the query efficiency is very low, in addition, the management is very complex, so we need to divide different sets of databases.

The previous article saw a lot of collections, people, system. indexes, system. users and so on, the set name also has certain restrictions, first cannot be empty "", cannot contain null characters, cannot have reserved characters $, starting with system is even worse, this is the prefix not reserved by the system set. We only need to use some easy-to-understand naming, and it is very easy for us to manage and operate on our own.

MongoDB also has a sub-set concept, that is, a set containing several sets, which is also easy to manage. For example, it is a little reluctant to put the basic information and nationality information of people in a set above, you can either write a document directly or use two child sets, one representing the basic information baseinfo and the other representing the nationality information countryinfo:

db.people.baseinfo.insert({"name" : "Mary", "age" : 10})db.people.countryinfo.insert("country" : "USA", "languge" : "english")

This example is far-fetched, but it is easy to understand. We can see from the above that we can directly insert without creating a set like people, which is a bit difficult to understand for MySQL users. If a table is not created, We can insert data to it, even worse, we can directly use any database without creating a database:

> show dbsadmin   0.078GBdhh_tp  0.078GBlocal   0.078GBtest    0.078GB> use templeswitched to db temple>dbtemple> show collections> db.people.insert({"name" : "Mary", "age" : 10})WriteResult({ "nInserted" : 1 })> show tablespeoplesystem.indexes> db.people.find(){ "_id" : ObjectId("539137ce90c0386ead60e4f4"), "name" : "Mary", "age" : 10 }

Check out. show dbs has no temple in all databases, but no error is reported when you use it directly, you can use the database to check which database you are using. show collections shows that no one set exists when you view all the sets, because the database does not exist. No error will be reported if data is inserted directly to the people set. After the query, the people set is generated, and there is a system. indexes set, data is indeed inserted into the people set, system. indexes stores the indexes in the set. MongoDB will check whether such a database is such a set when inserting data. If it does not exist, it will be automatically created, so we do not need to create our own set and define so many fields, the data type, length, whether the field can be empty, unique key, and so on are very convenient and practical.

3. Database

Multiple documents in MongoDB form a set, so multiple sets form a database. For example, the people and system. indexes above form a temple database. Each database in MongoDB is independent of each other and has independent permissions and is stored in different files.

The naming of apsaradb for MongoDB is also limited. It cannot contain spaces or empty characters or special characters. It should be all lowercase letters, up to 64 bytes. This is very important, the database name will eventually become a file in the system. You can open data/db and check that there will be files with the same name as your database, which contains the database data, the database name should also be easy to understand. In addition, some names cannot be used, such as admin. This is the root database and local is not enough. This database cannot be copied. In the future, config is related to sharding, these are all reserved database names.

The previous article also introduced how to start the MongoDB server. As mentioned in the previous article about starting the MongoDB client, you can execute the mongo specified option. Here, you can execute any javascript program or perform general operations on the database, add insert, delete, remove, find, update, and so on. This will be discussed later. There are also commands for deleting collections and databases:

> show tablespeoplesystem.indexes> db.people.drop()true> show tablessystem.indexes> use templeswitched to db temple> dbtemple> db.dropDatabase(){ "dropped" : "temple", "ok" : 1 }> show dbsadmin   0.078GBdhh_tp  0.078GBlocal   0.078GBtest    0.078GB

Db. dropDatabase () deletes the used database, and db. people. drop () deletes the people set. These APIs are easy to use.

4. Data Type

MongoDB has rich data types. The above name field is a string and the age field is a number. Of course, there are more than two types. JSON has only 6 data types, such as null, Boolean, number, String, array, and object. MongoDB adds some other data types based on JSON. Let's take a look at the data types of MongoDB:

Null: Indicates a control or non-existent field, for example, {"x": null }.

Boolean: Only two values are true and false.

32-bit integer: This type is not available in shell. javascript only supports 64-bit floating point numbers, so 32-bit integers are automatically converted.

64-bit integer: This type is unavailable in shell. shell uses a special embedded document to display 64-bit integers.

64-bit floating point number: The numbers in shell are of this type. Both {"x": 3.14} and {"x": 3} are floating point numbers.

Because javascript has only one numeric type, which is a 64-bit floating point type, the number from the shell in MongoDB is regarded as a 64-bit floating point type, and MongoDB supports three numeric types, therefore, the data in the database will be converted to a 64-bit floating point type after being modified using shell. A 64-bit integer cannot accurately represent the 64-bit floating point type. If a 64-bit integer is saved in MongoDB, if it can represent a 64-bit floating point, it will be displayed in a key-embedded document and the value is accurate. Otherwise, it will display a multi-key embedded document, which may be inaccurate.

If it is a 64-bit integer 3, the query in shell will look like this:

db.nums.findOne(){        "_id" : ObjectId("4c0beecfd096a2580fe6fa08"),        "myInteger" : {                "floatApprox" : 3    }}

If it is a 64-bit integer of 9223372036854775807, the query in shell will look like this:

db.nums.findOne(){        "_id" : ObjectId("4c0beecfd096a2580fe6fa08"),        "myInteger" : {                "floatApprox" : 9223372036854775807,                "top" : 2147483647,                "bottom" : 4294967295    }}

Top and bottom indicate high 32-bit and low 32-bit respectively.

String: A UTF-8 string can be represented as a string type, such as: {"name": "Mary "}.

Symbol: Shell does not support this type. shell converts the symbol type in the database to a string.

Object id: The Object id is the unique ID of 12 bytes of the document.

The document stored in MongoDB must have a key "_ id", which can be of any type. The default key is the ObjectId object. This key is not specified when we store the document, then MongoDB automatically adds such a key-value pair, which is a unique identifier and ObjectId uses 12 bytes of storage space.

Date: The Date type stores the number of milliseconds starting from the standard epoch, not the time zone, for example: {"x": new Date ()}.

In javascript, the Date object is used as the Date type of MongoDB. The creation Date object must use new Date () instead of Date (). The return value is a string representing the Date, rather than a real Date object.

Regular Expression: The document can contain regular expressions, which use the regular expression syntax of javascript, such as: {"x":/foobar/I }.

Code: The document also contains javascript code, such as: {"x": function (){/*...*/}}.

Binary data: Binary data can be composed of any byte string, but cannot be used in shell.

Maximum Value: BSON contains a special type, which indicates the maximum possible value. This type is not found in shell.

Minimum value: BSON contains a special type, indicating the possible minimum value. This type is not found in shell.

Undefined: The undefined type can also be used in this document, for example: {"x": undefined}

Array: A set or list of values can be expressed as an array, and the elements in the array can be different types of data, such as: {"x": ["a", "B ", "c", 20]}.

Embedded document: The document can contain other documents or be embedded into the parent document as values, for example, {"x": {"foo": "bar "}}.

In my current use cases, Boolean, number, String, date, array, and embedded documents are the most used.

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.