MongoDB Learning Notes (i)

Source: Internet
Author: User
Tags bulk insert findone getmessage mongoclient mongodb query

1.MongoDB Introduction MongoDB Introduction
MongoDB是面向文档的非关系型数据库,不是现在使用最普遍的关系型数据库,其放弃关系模型的原因就是为了获得更加方便的扩展、稳定容错等特性。面向文档的基本思路就是:将关系模型中的“行”的概念换成“文档(document)”模型。面向文档的模型可以将文档和数组内嵌到文档中。因此,实际中可以用一条数据表示非常复杂的结构。MongoDB没有预定义模式:文档的键(key)和值(value)不再是固定的类型和大小,而且根据需求要添加或者删除字段变得更容易了。由于没有模式需要更改,通常不需要迁移大量数据。不必将所有数据都放到一个模子里面,应用层可以处理新增或丢失的键。这样开发者可以非常容易地变更数据模型。实际应用中,随着数据量的增大,数据库都要进行扩展。扩展有纵向扩展和横向扩展。纵向扩展是使用计算能力更强的机器,也是最省力的方法,但是很容易达到物理极限,无论花多少钱也买不到最新的机器了。横向扩展就是通过分区将数据分散到更多的机器上。MongoDB的设计采用横向扩展。面向文档的数据模型使它很容易地在多台服务器之间进行数据分割。还可以自动处理跨集群的数据和负载,自动重新分配文档,以及将用户请求路由到正确的机器上。开发者根本不用考虑数据库层次的扩展问题,需要扩展数据库时,在集群中添加机器即可,MongoDB会自动处理后续的事情。MongoDB有如上各种特性,但为了达到这些,他也放弃了关系型数据库的某些功能如表连接join和复杂的多行事务。


Intuitive Understanding:

MongoDB's Advantages and disadvantages
    1. Fast! Based on memory, thermal data is stored in physical memory (not just indexes and small portions of data), which improves overall speed and efficiency.
    2. High Scalability! MongoDB's high availability and cluster architecture are highly scalable.
    3. Self-failover mechanism! In a replica set, when the main library encounters a problem and cannot continue to provide services, the replica sets will elect a new primary library to continue serving.
    4. Data in JSON format! MongoDB's Bson and JSON-formatted data are ideal for storing and querying document formats.
Disadvantage
    1. Less application Experience! Since the rise of NoSQL is short, application experience is less than relational database.
    2. As a result of the use of the relational database, it may cause the user to start the non-adaptation.
    3. No transaction mechanism! MongoDB itself does not have a transaction mechanism, and if it is necessary to implement the transaction mechanism in MongoDB, it is necessary to implement the transaction logically by itself through an additional table.
2.MongoDB vs MySQL
database Mong ODB MySQL
Database model non-relational relationship type
storage mode store in the format of a document of class JSON different engines have different storage methods
Query Statement MongoDB Query method (JavaScript-like function) SQL statement
Data processing method based on memory, storing hot data in physical memory for high-speed read and write different engines have their own features
Maturity Emerging databases, low maturity mature high
extensive NoSQL database, more complete and open source, the number of people growing open source database, growing market share
Transactional supports only single-document transaction operations, weak consistency support transactional operations
Space-occupying takes up space takes up little space
Join Operation MongoDB no join MySQL support join

Here is a comparison of the operation commands between MongoDB and MySQL:

MongoDB Basic knowledge and crud

1. Document: Equivalent to the "line" of a traditional relational database, but more complex than the information represented by traditional lines. For example:

{"Name": "Jack", "age": +, "sex": "Male"}

2. Collection (collection): This represents a set of documents in MongoDB, similar to a table in a relational database. But the table in MongoDB (which is the collection) is not modal, you can put a completely different document into the same collection. In practice, however, a pattern is implicitly defined for a particular set. Note: Collections do not exist when there are no documents in the collection. When the first document is inserted, the collection is created.
3. Database: In MongoDB, a set of collections can form a database. A MongoDB instance can host multiple databases. Each database has a separate permission control. In real-world applications, all data for an application is typically placed in a single database.
4. Data type: The document in MongoDB is similar to JSON. JSON is a simple data interchange format that supports only: null, Boolean, numeric, string, array, and object in terms of data types. These types of performance are not enough in some practical applications, such as JSON itself does not directly support the date type, for the number, JSON itself can not distinguish between integers and floating-point numbers, but also can not distinguish between 32-digit and 64-digit number. To do this, MongoDB preserves the various features of JSON and adds some data types to it.
1.null: A field that represents a null value or does not exist. In the shell, this means:{"x":null}
2. Boolean: There are two values, true and false. This is used in the shell:{"x":true}
3. Number: The number in the shell is 64-bit floating-point numbers, as in the shell{"x":3.14}And{"x":3}The values in both documents are 64-bit floating-point numbers.
4. String: This is the most widely used, the shell says:{"x":"hello world!"}
5. Date: This is the number of milliseconds that are stored in the data store, starting from the standard era, with no time zone information stored.
6. Regular Expressions: A document can contain regular expressions, using JavaScript's regular expression syntax, which is represented in the shell:{"x":/foobar/i}
7. Array: An array is a set of values that can be represented either as ordered objects (lists, stacks, queues, etc.) or as unordered objects (collections), which in the shell represent an array:{"things":["pie",3.14]}
8. Inline document: The value that corresponds to a key in another document as a whole document.
Other include binary data, code, etc.

Getting Started with MongoDB (shell basic operations)

Run MONGO to start the shell:

The shell is a full-featured JavaScript interpreter that can run arbitrary JavaScript programs. No example is done here.
The default database for MongoDB is "DB", and the database is stored in the data directory.
1. Select a database

#选择名test数据库use Tset

  


If you forget the database name, you can enter the following code to query all database names: "Show dbs" command to display a list of all data

Show DBS

  


To view the collection name in the database:

Show collections

  

Results:

The following table lists the terms that the RDBMS corresponds to MongoDB:

Insert Document

The Insert function inserts a document into the collection. Take a blog example. Create a variable called post (a JavaScript object) with three keys and corresponding properties. Insert Code:

Db.blog.insert (POST)



BULK INSERT

Db.blog.insertMany ([{"_id": 0},{"_id": 1},{"_id": 2}])

  

Querying documents

The query code is as follows:

Db.blog.find ()



The extra "_id" is the object that MongoDB automatically creates by default to the Objectid type. In a collection, each document is made up of a unique "_id", ensuring that each document in the collection is uniquely identified, it takes 12 bytes of storage and consists of 24 16 binary digits, which can be divided into four parts:

{0,1,2,3} {4,5,6} {7,8} {9,10,11}
Time stamp Machine code PID (thread code) Self-increment counter

If you insert a document without the "_id" key, the system automatically creates one for us.
If you want to view only one document, you can use FindOne:

Db.blog.findOne ()

  

Query a specific document then you will add the query criteria in JSON form, for example:

Db.blog.find ({"title": "My blog Post"})

  

The above example is similar to the WHERE statement: where title = ' My Blog Post ';

Modifying a document

If you add a comment feature to your blog, you'll need to add a new key-value to save the comments array.

Post.comments = []

Then replace the old version with the new version of the document:

Db.blog.update ({"title": "My blog Post"},post)

Using modifiers:
"$Set":用来指定一个字段的值,若字段不存在,则创建它。
Db.users.update ({"Sex": "Male"},{"$Set": {"gift": "Happy birthday! "}})/* This will only update one document, to update multiple documents, you need to set the fourth parameter of update to True*/db.users.update ({" Sex ":" Male "},{" $Set ": {" gift ":" Happy birthday! "}},false,true)
"$inc":用来增加已有键的值,若键不存在,就创建它。(与"$Set"类似,专门用来增加数字的,只能用于整形,长整型,双精度浮点型)
Db.games.update ({"Game": "Pinball", "User": "Joe"},{"$inc": {"score": 50}})
"$push":会向已有的数组末尾加入一个元素,若数组不存在,则创建数组。与"$each"自操作符一同使用可以一次添加多个值。
Db.stock.ticker.update ({"_id": "1"},{"$push": {"hourly": {"$each": [562.667,562.790,562.123]}}})
"$addToSet":可以避免重复插入。若数组内已有相同数据,则不差入。与"$each"自操作符一同使用可以一次添加多个值。
Db.users.update ({"_id" "1},{" $addToSet ": {" emails ":" [email protected] "}})
"$push":删除数组里的元素.("$pop":将数组看成队列或栈,从两端删除。"$pull":将所匹配到的数组中的值删除,而不是只删除一个)
Delete a document
Db.blog.remove ({"title": "My blog Post"})


Delete Entire collection with drop ()

Db.blog.drop ()
Index

MongoDB uses the Ensureindex () method to create an index.

Db. Collection_name.ensureindex ({key:1})

The Key value in the syntax is the index field you want to create, 1 for the specified index in ascending order, or 1 if you want to create the index in descending order.
Of course, you can also index multiple fields

Db.col.ensureIndex ({"title": 1, "description":-1})
Pipeline Aggregation

MongoDB's aggregation pipeline passes the MongoDB document to the next pipeline processing after a pipeline has finished processing. Pipeline operations can be repeated.
Expression: Processes the input document and outputs it. The expression is stateless and can only be used to calculate the document for the current aggregated pipeline and cannot process other documents.
Here we introduce several common operations in the aggregation framework:

    • $project: Modifies the structure of the input document. You can use it to rename, add, or delete fields, or to create calculations and nested documents.
Db.article.aggregate ({$project: {title:1, Author:1,}});
    • $match: Used to filter data and only output documents that match the criteria.
Db.articles.aggregate ([{$match: {score: {$gt: $, $lte: +}}},{$group: {_id:null, Count: {$sum: 1}}]);
    • $limit: Used to limit the number of documents returned by the MongoDB aggregation pipeline.
Db.article.find (). Limit
    • $skip: Skips the specified number of documents in the aggregation pipeline and returns the remaining documents.
Db.article.aggregate ({$skip: 5});
    • $group: Groups The documents in the collection to be used for statistical results.

    • $sort: Sorts the input documents after the output.

Java Operation MongoDB Connection database

To connect to the database, you need to specify the database name and MONGO will automatically create the database if the specified database does not exist.
Jar Package Required: Mongo-java-driver-3.2.2.jar
The Java code to connect to the database is as follows:

1 Importcom.mongodb.MongoClient;2 Importcom.mongodb.client.MongoDatabase;3  Public classmongodbjdbc{4  Public Static voidMain (String args[]) {5 Try{6 //Connect to MongoDB service7Mongoclient mongoclient =NewMongoclient ("localhost", 27017 );8 //connecting to a database9Mongodatabase mongodatabase = mongoclient.getdatabase ("Test");TenSystem.out.println ("Connect to database successfully"); One}Catch(Exception e) { ASystem.err.println (E.getclass (). GetName () + ":" +e.getmessage ()); - } - } the}

To create a collection:
We can use CreateCollection () in the Com.mongodb.client.MongoDatabase class to create the collection
The code snippet is as follows:

Importcom.mongodb.MongoClient;Importcom.mongodb.client.MongoDatabase; Public classmongodbjdbc{ Public Static voidMain (String args[]) {Try{//Connect to MongoDB serviceMongoclient mongoclient =NewMongoclient ("localhost", 27017 );//connecting to a databaseMongodatabase mongodatabase = mongoclient.getdatabase ("Test"); System.out.println ("Connect to database successfully"); Mongodatabase.createcollection ("Test"); System.out.println ("Collection Creation succeeded");}Catch(Exception e) {System.err.println (E.getclass (). GetName ()+ ": " +e.getmessage ()); }}}

Insert Document
// Insert Document /**  */new Document ("title", "MongoDB"). Append ("description", "Database" ). Append ("likes", [+]). Append ("by", "Fly"); ListNew arraylist<document>();d ocuments.add (Document); Collection.insertmany ( Documents); SYSTEM.OUT.PRINTLN ("Document insertion succeeded");

Querying documents
// Retrieving all Documents /**  */finditerable<Document> finditerable = collection.find (); Mongocursor<Document> mongocursor = finditerable.iterator ();  while (Mongocursor.hasnext ()) {System.out.println (Mongocursor.next ());}

Modifying a document
// update the document to modify the document in document LIKES=100 to likes=200 New Document ("$set",new document ("likes")); // Retrieving View results finditerable<document> finditerable = collection.find (); Mongocursor<Document> mongocursor = finditerable.iterator ();  while (Mongocursor.hasnext ()) {System.out.println (Mongocursor.next ());}

Delete a document
// Delete the first document that meets the criteria Collection.deleteone (Filters.eq ("likes"); // Delete all eligible documents Collection.deletemany (Filters.eq ("likes"); // Retrieving View results finditerable<document> finditerable = collection.find (); Mongocursor<Document> mongocursor = finditerable.iterator ();  while (Mongocursor.hasnext ()) {System.out.println (Mongocursor.next ());}

MongoDB Learning Notes (i)

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.