Basic concepts of MongoDB & amp; reference documents, basic concepts of mongodb

Source: Internet
Author: User
Tags findone

Basic concepts of MongoDB & amp; document reference, basic concepts of mongodb
Basic concepts of MongoDBThe following is a comparison between some SQL terms and MongoDB terms:

SQL terms/concepts MongoDB terms/concepts Description/Description
Database Database Database
Table Collection Database tables/Sets
Row Document Data Record line/Document
Column Field Data Field/Field
Index Index Index
Table joins ? Table connection, not supported by MongoDB
Primary key Primary key Primary Key. MongoDB automatically sets the _ id field as the primary key.


Database a single mongodb can create multiple databases ,? The default database is db, which is stored in the directory specified by the startup parameter dbpath. A single MongoDB instance can accommodate multiple independent database databases, each database has its own collection and permissions, and different databases are stored in different files;
The following are some basic commands for viewing the database:
?
# Display all mongodb databases under the current permission
show dbs ? 
show databases 
?
# Display the name of the current database object or set
db
?
# Connecting (using) the specified database
use data_name
Mongodb has the following reserved databases, Admin: From the Perspective of permissions, this is a "root" database. If a user is added to the database, the user automatically inherits the permissions of all databases. Some specific server commands can only be run from this database, such as listing all databases or disabling servers;
Local: This data will never be copied and can be used to store any set of data limited to a local server;
Config: When Mongo is used for fragment settings, the config database is used internally to save information about the fragment;

The collection colletioncollection is a document group of mongodb, which is similar to the table in RDBMS. The collection exists in the database and has no fixed structure. That is, data of different formats and types can be inserted into the collection, however, data inserted into the set is usually correlated. For example, you can insert the following documents with different data structures into the document :?
{"site":"www.baidu.com"}
{"site":"www.google.com","name":"Google"}
Here are the instructions for viewing collections:
?
use local
Show collections? ? # Display all collections in the current db
Show tables? ? ? ? ? # Same as above
The collection name cannot start with "system.", and it is best not to have system reserved characters;
Documentdocument is a key-value Pair (BSON). mongo documents do not need to set the same fields, and the same fields do not need the same data type; an example of a simple document is as follows:
?
{"site":"www.google.com","name":"Google"}
The value in document can be various data types supported by mongodb, which are case sensitive and case sensitive. The same key cannot exist in a document, and the document key is of the string type (generally the UTF-8 encoding format );
Metadata the metadata of each database in mongodb is stored in . System .*? In the collection below, the main colletion is as follows:
Dbname. system. namespaces List all namespaces
Dbname. system. indexes List all indexes
Dbname. system. profile Contains the profile information of the database.
Dbname. system. users List all users who can access the database
Dbname. local. sources Server Information and status that contain the replication peer (slave)

The following restrictions apply to modifying objects in a system set. {System. indexes} inserts data to create indexes, but the table information is unchangeable. {system. users} is changeable; {system. profile} can be deleted;

Data Type

? MongoDB supports multiple data types. The following are common data types;

String String. Common data types used to store data. In MongoDB, UTF-8-encoded strings are valid.
Integer Integer value. Used to store numeric values. The server where the environment is located can be divided into 32-bit or 64-bit.
Boolean Boolean value. Stores boolean values (true/false ).
Double Double-precision floating point value. Used to store floating point values.
Min/Max keys Compare a value with the minimum and maximum values of BSON (Binary JSON) elements.
Array Stores an array, list, or multiple values as one key.
Timestamp Timestamp. Record the document modification or addition time.
Object Embedded document.
Null Creates a null value.
Symbol Symbol. The data type is basically the same as the string type, but the difference is that it is generally used in languages with special symbol types.
Date Date and time. The current date or time is stored in UNIX time format. You can specify your own Date and time: Create a Date object and input the year, month, and day information.
Object ID Object ID. The ID used to create a document.
Binary Data Binary data. Stores binary data.
Code Code type. It is used to store JavaScript code in the document.
Regular expression Regular Expression type. Stores regular expressions.


MongoDB ObjectId? The ObjectId of mongodb is used to represent the _ id key of a document, which is usually generated automatically. ObjectId is a 12-byte BSON data in the following format :?
_id : ObjectId("5a83c0d8a04c12209d79eea1")
<Timestamp-4 bytes> <machine identification code-3 bytes> <process ip address (PID)-2 bytes> <random number-3 bytes>
Create a new ObjectId?
> newObjectId = ObjectId()
# You can use your own ObjectId instead of the automatically created ObjectId.
> myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
Get the document Timestamp?
>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()
ISODate("2014-04-12T21:49:17Z")
ObjectId to string?
> new ObjectId().str
5a85711e049466e633bc36ba


The relationship between apsaradb for MongoDB and apsaradb for MongoDB indicates the logical connection between multiple documents. You can establish a logical connection between documents through embedding and referencing. The relationships in MongoDB include: 1: 1?
1: N?
N: 1?
N: N?
The following are two simple document structures: UserDocument?
{
 ? "_id":ObjectId("52ffc33cd85242f436000001"),
 ? "name": "Tom Hanks",
 ? "contact": "987654321",
}
AddressDocument?
{
 ? "_id":ObjectId("52ffc4a5d85242602e000000"),
 ? "building": "22 A, Indiana Apt",
 ? "pincode": 123456,
 ? "city": "Los Angeles",
 ? "state": "California"
} 
The relationship between user and address is 1: N. You can use either of the following two methods to represent the relationship:
Embedded relationshipThe address can be embedded into the user document. This advantage is intuitive and convenient to search for. However, as the data volume increases, the read/write speed will be greatly affected ;?
{
 ? "_id":ObjectId("52ffc33cd85242f436000001"),
 ? "contact": "987654321",
 ? "name": "Tom",
 ? "address": [
 ? ?  {
 ? ? ? ? "building": "22 A, Indiana Apt",
 ? ? ? ? "pincode": 123456,
 ? ? ? ? "city": "Los Angeles",
 ? ? ? ? "state": "California"
 ? ?  },
 ? ?  {
 ? ? ? ? "building": "170 A, Acropolis Apt",
 ? ? ? ? "pincode": 456789,
 ? ? ? ? "city": "Chicago",
 ? ? ? ? "state": "Illinois"
 ? ?  }
 ?  ]
} 
The search operation is as follows :?
# Find the first address of user Tom
> db.users.findOne({name:"Tom",address:1})

The reference link references the user data document and the user address data document separately, and establishes the relationship by referencing the Document id field. There are two ways to establish document reference: 1. Manual referenceObjectId ??
{
 ? "_id":ObjectId("52ffc33cd85242f436000001"),
 ? "contact": "987654321",
 ? "name": "Tom Benzamin",
 ? "address_ids": [
 ? ?  ObjectId("52ffc4a5d85242602e000000"),
 ? ?  ObjectId("52ffc4a5d85242602e000001")
 ? ]
}
The search operation is as follows:
?
# Find the first address of user Tom
> var result = db.users.findOne( {name:"Tom",address_ids:1} )
> var address = db.address.find( {'_id':{$in:result["address_ids"]}} )
2. DBrefs reference can be used to compile reference addresses. When defining ObjectId, you can define the Set Name and database name. This makes it easier to query. The reference format of DBreds is: {$ ref: colletcion_name, $ id: objectId_val, $ db: database_name :? } $ Ref: Set Name;
$ Id: The referenced id;
$ Db: name of the referenced database. Optional;
Assume that the address document is located in the address_unit set of the testdb database. The user document is as follows :?
{
 ? "_id":ObjectId("53402597d852426020000002"),
 ? "contact": "987654321",
 ? "name": "Tom",
 ? "address":[
 ? ? ? {
 ? ? ? ? ? "$ref": "address_unit",
 ? ? ? ? ? "$id": ObjectId("534009e4d852427820000002"),
 ? ? ? ? ? "$db": "testdb" 
 ? ? ?  },
 ? ? ?  {
 ? ? ? ? ? "$ref": "address_unit",
 ? ? ? ? ? "$id": ObjectId("53433454d852427820000002"),
 ? ? ? ? ? "$db": "testdb" 
 ? ? ?  },
 ?  ]
}
The search operation is as follows:
?
# Find the first address of user Tom
> var user = db.users.findOne( {name:'Tom'} )
> var addrRef = user.address[0]
> db[addrRef.$ref].findOne( {"_id":(addrRef.$id)} )

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.