MongoDB learning summary (2) - basic operation commands (add, delete, modify, check)

MongoDB learning summary (2) – basic operation commands (add, delete, modify, check)

The previous article introduced the installation of MongoDB on the Windows platform. This article introduces some basic operating commands of MongoDB. Let’s go straight to the topic and introduce it one by one with simple examples. > View all databases (show dbs) > Insert document (insert) Format: > db.COLLECTION_NAME.insert(document) All data stored in the collection is in BSON format. BSON is a binary storage format similar to json, referred to as Binary JSON. Next, insert two pieces of data into the student collection. Since the operation window is a Javascript shell,, you can also use it herejs. Since the document is stored in the “K-V” format, <span lang="en The Value in -US”>JSON can be a string, an array, or An embedded JSON object, so BSON also same. > Query document (find) Format: > db .COLLECTION_NAME.find() find() method displays all documents. Note “_id”: This field is the GUID added by the database by default to ensure the uniqueness of the data. . writeConcern: Optional, the level at which the exception is thrown. 1) Basic modifications 2)$set (Set the value directly) Change jack’s age to 21 age. 3)$inc (Added on the basis of the original value of the numeric key value) Increase…

How the django framework uses the views.py function to perform operations on tables  Add, delete, modify and check

How does the django framework use the views.py function to add, delete, modify, and query tables?

This article will explain in detail how the Django framework uses the views.py function to add, delete, modify and query tables. The editor thinks it is quite practical, so I share it with you as a reference. I hope you will read it. You can gain something after finishing this article. The details are as follows: Models have the following types of table creation: One-to-one: ForeignKey(“Author “,unique=True), OneToOneField(“Author”) One-to-many: ForeignKey(to=”Publish”,to_field=”id”,on_delete.CASCADE) Many To many: ManyToManyField(to=”Author”) First we create a few tables from django.db import models #Create your models here. class AuthorDetail(models.Model): gf=models.CharField(max_length=32) tel=models.CharField(max_length=32) class Author(models.Model): name=models.CharField(max_length=32) age=models.IntegerField() # Establish a one-to-one relationship with AuthorDetail # ad=models.ForeignKey(to=”AuthorDetail”,to_field=”id”,on_delete=models.CASCADE,unique=True) ad=models.OneToOneField(to=”AuthorDetail”,to_field=”id”,on_delete=models.CASCADE,) class Publish(models.Model): name=models.CharField(max_length=32) email=models.CharField(max_length=32) addr=models.CharField(max_length=32) class Book(models.Model): title=models.CharField(max_length=32,unique=True) price=models.DecimalField(max_digits=8,decimal_places=2,null=True) pub_date=models.DateField() # Establish a one-to-many relationship with Publish, and the foreign key field is established on the many side publish=models.ForeignKey(to=”Publish”,to_field=”id”,on_delete=models.CASCADE) # Establish a many-to-many relationship with the Author table. ManyToManyField can be built in either of the two models to automatically create the relationship table book_authors authors=models.ManyToManyField(to=”Author”) Description: OneToOneField means creating a one-to-one relationship. to indicates which table needs to create a relationship to_field indicates the associated field on_delete=models.CASCADE indicates cascade delete . Assuming that a record is deleted from table a, the corresponding record…

Django (16) model operation (add, delete, modify, check)

In the ORM framework, all model-related operations, such as add/delete, etc. In fact, they are all operations mapped to a piece of data in the database. Therefore, model operations are operations on data in database tables. Add a model to the database: Add the model to the database. First you need to create a model. Creating a model is very simple, just like creating an ordinary Python object. After creating the model, you need to call the save method of the model, so that Django will automatically convert the model into a SQL statement and then store it in the database. The sample code is as follows: class Book(models.Model): name = models.CharField(max_length=20,null=False) desc = models.CharField(max_length=100,name=’description’,db_column=”description1″) pub_date = models.DateTimeField(auto_now_add=True) book = Book(name=’python encyclopedia’,desc=’learn python’) book.save() # Save to database Query data Looking for data is achieved through the objects objects under the model. Find all data To find all the data under the table corresponding to the Book model. Then the sample code is as follows: books = Book.objects.all() The above will return all data under the Book model. Data filtering When searching for data, sometimes it is necessary to filter some data. Then you need to call the filter method…

Simple use of monogoDB (add, delete, modify, check, update, etc.)

Simple use of monogoDB (add, delete, modify, check, update, etc.)

Article Directory Preparation Related concepts of database Connect with database Create collection Create document (specific data) Query document (data) Delete document (data) Update document La la la Preparation First, make sure MongoDB is started. If not, run cmd as administrator net start mongoDB Secondly, you need to install third-party modules npm install mongoose And import it const mOngoose= require(‘mongoose’); Database related concepts Terminology Explanation database Database (data warehouse) collection Set, a set of data, can be understood as an array in js document Document, a specific piece of data, can be understood as a js object field Field, the attribute name in the document, It can be understood as object attributes in js A database software can contain multiple data warehouses, and each data warehouse can contain Multiple data sets can also contain multiple documents (specific data) in each data set, and each set can contain multiple fields Look at the following pictures p> The data warehouse includes: admin, config, local (these three are included with the software), playground (created by yourself) Collection (with playground is Li): posts, students, tests, users Documents: There are 3 documents on the right side of the picture below Field: _id (soft armor itself What…

$Django template layer (template import, inheritance), single table * details (add, delete, modify, query based on double underscore), static static file configuration

0Use the django environment in python scripts import osif __name__ == ‘__main__’: os.environ.setdefault(” DJANGO_SETTINGS_MODULE”, “untitled15.settings”) import django django.setup() from app01 import modelsmodels.Book.objects.filter(name=’123′) 1 Template import–>Template reuse 1 Write a template 2 Import in another template:{% include ‘template.html’%} 2 Template inheritance (equivalent to __init__) 1 Write a master and leave an expandable area (box). You can leave multiple Boxes (the more boxes you leave, the higher the scalability) {%block Name%} Yes Write content {%endblock%} {% include ‘left.html’ %} {% block c1 %} wwww {% endblock c1 %} 2 Used in child template: {% extend ‘master.html’%} {%block Name%} {{block.super}} #The content of the master box can be inherited {{block.super}} #The content of the master box can be inherited The content of the child template {%endblock Name% } {% extends ‘1.html’ %}{# inheritance#}{# {{ block.super }} {# invalid#}{#123321312312412412512 {# invalid#}{ % block c1 %} {# Equivalent to the subclass definition __init__. If it is not defined, use the parent class. If it is defined, use your own #} {{ block.super }} {{ block.super }} Hehe Hehe{% endblock c1 %} 3 Static file related 1 Hard-coded static files: /static/css/mycss.css“> 2 Use the static tag function: –{%load static%} #load is a static.py file #static return…

mongodb view, create, modify, delete index

Indexes can usually greatly improve the efficiency of queries. Without indexes, MongoDB must scan each file in the collection and select those records that meet the query conditions when reading data. The query efficiency of scanning the entire collection is very low. Especially when processing a large amount of data, the query can take dozens of seconds or even minutes, which is very fatal to the performance of the website. An index is a special data structure that is stored in a data collection that is easy to traverse and read. An index is a structure that sorts the values ​​of one or more columns in a database table Note: col in the text is your own collection name View index getIndexes() View all indexes of the collection > db.col.getIndexes() > getIndexKeys() View all index keys in the collection > db.col.getIndexKeys() > totalIndexSize() View the total size of the indexes in the collection > db.col.totalIndexSize() > getIndexSpecs() View detailed information of each index in the collection > db.col.getIndexSpecs() > Create index MongoDB uses the createIndex() method to create indexes. Note that before version 3.0.0, the index creation method was db.collection.ensureIndex(). Later versions used the db.collection.createIndex() method. ensureIndex() can still be…

Java connection database add, delete, modify, check tool class

java connection database add, delete, modify, check tool class Database operation tools, because the paging conditions of each manufacturer’s database are different, currently support paging queries of Mysql, Oracle, and Postgresql It has been tested in the Postgresql environment, but has not been tested in other databases. SQL statements need to be in precompiled form The code is as follows:package db; import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.reflect.Field;import java.sql.Connection;import java.sql.Date;import java.sql.Driver;import java.sql.DriverManager; import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.sql.Time; import java.sql.Timestamp;import java.util.ArrayList;import java.util.List;import java.util.regex.Matcher;import java.util. regex.Pattern; import javax.naming.NamingException;import javax.sql.DataSource; /** * Database query tool class * Use precompiled sql * * @author XueLiang * */public class DBUtil { private static String driver; private static DataSource ds = null; private static String url = “jdbc:postgresql://192.168.56.101/db”; private static String user = “test”; private static String password = “12345678”; static { try { Class.forName(“org.postgresql.Driver” ); //ds = (DataSource)SpringContextUtil.getBean(“dataSource”); } catch (Exception e) { e.printStackTrace(); } } /** * Establish connection * * @return con Connection * @throws Exception */ private static Connection getConnection() throws Exception { Connection cOnn= DriverManager.getConnection(url, user, password);// Connection cOnn= ds.getConnection(); Driver d = DriverManager.getDriver(conn.getMetaData().getURL()) ; driver = d.getClass().getName(); return conn; } /** * Close the connection * * @param conn *…

Java operates MySQL, creates JDBC tool classes, uses Druid connection pool technology, and implements CRUD (add, delete, modify, query)

Java operates MySQL, creates JDBC tool classes, uses Druid connection pool technology, and implements CRUD (add, delete, modify, query)

Requirements:Use JDBC to create a table,Table name student,field contains id,name(username), class(class_and_grade) student number(student_number), gender(sex), Age, email address. And add corresponding constraints. Implement CRUD for the table (note the use of additions, deletions and modifications. 1. Create a module named JDBC 2. Add the resource druid.proporties 3. Connect to the MySQL database 4. Configure JDBC tool class package com.cn.zpark.utils; import java.sql.*; public class JDBCUtils { // Define data path connection information private static String url = “jdbc:mysql://localhost: 3306/my_druid?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8”; private static String user = “root”; private static String pwd = “ root”; public static Connection getConn() throws Exception {//Register the driver Class.forName(“com.mysql.jdbc.Driver”);//Return the connection object return DriverManager.getConnection (url, user, pwd);}public static void close(Connection conn, ResultSet res, Statement… stat){try {if(res != null){res.close();} for (Statement statement : stat) {if(statement != null){statement.close();}}assert conn != null;conn.close();} catch (SQLException e) {e .printStackTrace();}} } 5. Start creating table student Code: package com.cn.zpark; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java .sql.Statement; public class JDBCCreateTable { public static void main(String[] args) { // Define connection database information String url &#61 ; “jdbc:mysql://localhost:3306/my_druid?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8”; String user = “root”; String pwd = “root”; Connection conn = null; Statement stat = null; try {// 1. Register Driver Class.forName(“com.mysql.jdbc.Driver”); // 2. Get the connection…

Java development learning (41) MyBatisPlus standard data layer (add, delete, check, modify, paging) development

1. Standard CRUD usage What are the standard CRUD functions and what methods does MyBatisPlus provide to use them? Let’s take a look at the picture first: p> 1.1 Environment preparation The environment used here is the environment used in Java Development Learning (Forty) – MyBatisPlus Getting Started Cases and Introduction 2. New addition In Before adding new ones, we can analyze the new methods: int insert (T t) T: Generic, added to save new data int: Return value, 1 is returned after the addition is successful, 0 is returned if the addition is not successful Perform new operations in the test class: @SpringBootTestclass Mybatisplus01QuickstartApplicationTests {​ @Autowiredprivate UserDao userDao;​@Testvoid testSave() {User user = new User();user.setName(“Dark Horse Programmer”);user.setPassword(“itheima”);user.setAge(12); user.setTel(“4006184000”);userDao.insert(user);}} After executing the test, a piece of data will be added to the database table. But the primary key in the data ID is a bit long, so where does this primary key ID come from? What we want more is for the primary key to auto-increment, which should be 5. This is the primary key ID generation strategy we will introduce later. For this issue, we will temporarily Let it go first. 3. Delete Before deleting, we can analyze the deletion…

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索