MongoDB fast practice and basic principles

Detailed explanation of basic concepts of MongoDB

Mongo is the middle part of humongous, which means "huge and incomparable" in English. Therefore, Mongodb can be translated into "huge database", and the more elegant name is "massive database". Mongodb is a non relational database. When it comes to non relational databases, the most significant feature that distinguishes it from relational databases is that there is no SQL statement, and the data has no fixed data type. The SQL statement used in relational databases has a history of more than 40 years since IBM invented it, but today, developers generally don't like it, Because its basic idea is inconsistent with the programmer's idea of programming. Later, the so-called NoSQL wind refers to those data storage systems that do not use SQL as the query language, and the document database Mongodb is the representative of NoSQL

Characteristics of MongoDB

  • A record in MongoDB is a document, which is a data structure composed of fields and value pairs. A MongoDB document is similar to a JSON object. Field values can include other documents, arrays, and document arrays. MongoDB data model is the same as the representation of your objects in memory. It is a clear object model.

  • Document objects with different fields (types) can be included in the same collection: the fields of the same collection may be different
  • When modifying the data mode online, the application and database do not need to be offline

The main concepts of relational database and document database correspond

*Relational databaseDocument database
Model entitysurfaceaggregate
Model propertiescolumnfield
Model relationTable AssociationEmbedded array, reference field association

MongoDB fast combat

MongoDB installation

  • Get the installation package and unzip it
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.4.10.tgz
tar ‐xvzf mongodb-linux-x86_64-rhel70-4.4.10.tgz

  • Configure environment variables
vi /etc/profile  

export MONGODB_HOME=/usr/local/mongo/mongodb-linux-x86_64-rhel70-4.4.10
export PATH=$PATH:$MONGODB_HOME/bin  

  • Create data directory
mkdir ‐p /data/db # This path is the default data storage path of MongoDB
  • Start MongoDB service
mongod # If you do not want to use the default data directory, you can specify the path by adding the ‐ dbpath parameter

Or you need to specify -- logpath or - syslog when starting from the background. And you need to create the output file.

mongod --logpath /data/db/logpath/output --fork

Client use - mongo shell

mongo shell, which is used to operate the javascript client interface of MongoDB

  • Connection service
mongo ‐‐host <HOSTNAME> ‐‐port <PORT> 
# If all default parameters are used locally, you can also ignore all parameters directly
mongo
  • Set password
use admin # To set the password, you need to switch to the admin library
db.createUser( 
 { 
	 user: "skq", 
	 pwd: "123",
	 roles: [ "root" ] 
 } 
)
show users # View all user information

  • Stop service, exit exit mongo
db.shutdownServer() # Stop service

  • Start and connect in authorized mode
    There is a problem here. We can't connect successfully according to the following instructions for the time being
mongod ‐‐auth
mongo ‐u skq

Based on security considerations, MongoDB only binds the local loopback IP 127.0.0.1 after installation by default. You can specify the bound IP when starting the service. For example, only access through IP 192.168.1.104 is allowed,
mongod ‐‐bind_ip 192.168.1.104
The following commands are used for connection
mongo ‐host 192.168.1.104 ‐u skq

Detailed explanation of MongoDB core operation and principle

Create databases, collections, documents

//writeConcern is an optional field with security level  
db.collection.insertOne(  doc ,  {  writeConcern: Security level} )

writeConcern defines the write security level of this document creation operation
In short, the secure write level is used to judge whether a database write operation is successful. The higher the secure write level, the lower the risk of data loss. However, the delay of write operation may also be higher. writeConcern determines how many nodes a write operation falls on before it is successful.

The values of writeConcern include

  • 0: initiate a write operation, regardless of success
  • 1. Maximum number of data nodes in the cluster: the write operation needs to be copied to the specified number of nodes before it is successful
  • majority: the write operation needs to be copied to most nodes to be successful. The program initiating the write operation will block until the write operation reaches the specified number of nodes
use demo

db.members.insertOne({"name":"zhangsan",age:19});


show tables
show collections
db.members.find();
db.members.insertOne({"_id":1,"name":"zhangsan",age:19});

When inserting a document, if the specified primary key is not displayed, MongoDB will create a primary key by default, and the field is fixed to_ id,ObjectId() can quickly generate a 12 byte id as the primary key. The first four bytes of ObjectId represent the generation time of the primary key, accurate to seconds. The primary key id is generated by the client driver. To some extent, it represents the order, but the order is not guaranteed. You can obtain the creation time through ObjectId ("id value"). getTimestamp().

db.members.insertMany([{"_id":100,"name":"lisi",age:19},{"_id":100,"name":"lisi2",age:19},{"_id":101,                                                        "name":"lisi3",age:19}],{"ordered":true});


db.members.insertMany([{"_id":100,"name":"lisi",age:19},{"_id":100,"name":"lisi2",age:19},{"_id":101,                                                        "name":"lisi3",age:19}],{"ordered":false});


ordered: whether to write in order. When writing in order, it will exit once an error is encountered. The remaining documents will not be written out of order whether they are correct or not. As long as the documents can be written correctly, they will be written correctly, regardless of whether the previous documents are wrong documents

db.inventory.insertMany([  { item: "journal", qty: 25, status: "A", size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] },  { item: "notebook", qty: 50, status: "A", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] },  { item: "paper", qty: 10, status: "D", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank", "plain" ] },  { item: "planner", qty: 0, status: "D", size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] },  { item: "postcard", qty: 45, status: "A", size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ] }  ]);

db.inventory.find();
db.inventory.find().pretty();

MongoDB organizes data in the form of a collection, which is equivalent to a table in a relational database. If the collection does not exist, a collection will be automatically created when you operate on the nonexistent collection, as shown below

Condition query:

db.inventory.find({"_id" : ObjectId("61a1b1061df00200ed561724")}).pretty();

Accurate equivalent query

db.inventory.find({"qty" : 45,"status" : "A"}).pretty();

Multi condition query

db.inventory.find( { "size.uom": "in" } );

Nested object precise query

db.inventory.find( { }, { item: 1, status: 1 } );

Returns the specified field
It returns by default_ The id field can also be specified_ id:0, no return_ id field

db.inventory.find({$and:[{"qty":45},{"status":"A"}]}).pretty();

Condition query and

db.inventory.find({$or:[{"qty":45},{"status":"A"}]}).pretty();

Conditional query or

Mongo query criteria and SQL query cross reference table

SQLMQL
A < > 1 or a= one{ a : {$ne: 1}}
a>1{ a: {$gt:1}}
a>=1{ a: {$gte:1}}
a<1{ a: {$lt:1}}
a<=1{ a: { $lte:1}}
in{ a: { $in:[ x, y, z]}}
not in{ a: { $nin:[ x, y, z]}}
a is null{ a: { $exists: false }}

The difference between insertone, inertmany and insert

  • insertOne, and insertMany commands do not support the explain command
  • insert supports the explain command

Composite primary key

db.product.insertOne({_id:{"product_name":"Apple","product_type":"6s"},create_time:new Date()})



Note that if the field order of the composite primary key is changed, it will be created as different objects, even if the contents are completely the same

Logical operator matching

$not: documents whose matching filter criteria are not tenable
$and: documents matching multiple filter criteria at the same time
$or: documents matching at least one filter condition
$nor: matches documents that do not meet multiple filter criteria

 db.members.insertMany([ { nickName:"Cao Cao", points:1000 },{ nickName:"Liu Bei", points:500 }])

db.members.find({points: { $not: { $lt: 100}}} );

$not also filters out documents that do not contain query fields

db.members.find({$and : [ {nickName:{ $eq : "Cao Cao"}}, {points:{ $gt:500}}]});


$and can be omitted when acting on different fields

When acting on the same field, it can be simplified to

db.members.find(  {$or : [  {nickName:{ $eq : "Liu Bei"}},  {points:{ $gt:1000}}]}  )

If they are all equivalent queries, the results of $or and $in are the same

Field matching

db.members.find({points:{$exists:true}})

$exists: matches documents containing query fields

db.members.count();
db.members.find().skip(1).count(true);

By default, the count here does not consider the effects of skip and limit. If you want to consider limit and skip, you need to set it to true. In distributed environment, count does not guarantee the absolute correctness of data

db.members.find().sort({ponints:1})

1 indicates from small to large, and - 1 indicates reverse sorting
When sort, skip and limit are applied at the same time, the order of application is sort, skip and limit

db.movies.insertMany([{name:"War wolf",tag:["action","Military Brigade","warm blood"]}])

db.movies.find({},{_id:0,tag:{$slice:1}})

Document projection: data can be returned selectively
Projection setting: {field: < 1:1 indicates that it needs to be returned, 0: indicates that it does not need to be returned, it can only be 0, or 1. It is not a primary key field, and 0 or 1 >}

$slice returns some elements in the array
slice:
1: First element of array
-1: Last element
-2: The last two elements
Slice [1,2]: the relationship between skip and limit

db.movies.find({},{_id:0,name:1,tag:{$elemMatch:{$eq:"Military Brigade"}}})

You can also use elementMatch to match array elements

update operation

The updateOne/updateMany method requires that the update condition part must have one of the following, otherwise an error will be reported
$set adds a field to the qualified document, and if there is such a field, its value will be modified
$unset to delete a field for qualified documents
$push: add an object to the bottom of the array
$pop: deletes an object from the bottom of the array
$pull: if the specified value matches, delete the corresponding object from the array
$pullAll: if any value matches, delete the corresponding object from the data
$addToSet: if it does not exist, add a value to the array

db.userInfo.insert([  { name:"zhansan",  tag:["90","Programmer","PhotoGrapher"]  },  { name:"lisi",  tag:["90","Accountant","PhotoGrapher"]  }]);

db.userInfo.updateMany(  {tag:"90"},  {$set:{flag:1}}  );

db.userInfo.find( {$or: [{tag:"Accountant"}, {tag:"Programmer"} ] });

db.userInfo.updateMany(  {tag:"90"},  {$unset:{flag:1}}  );

db.userInfo.updateOne(  {name:"lisi"},  {$inc:{age:-1}}  );

db.userInfo.updateOne(  {name:"lisi"},  {$mul:{age:10}}  );

remove document

db.userInfo.remove({name:"lisi"},{justOne:true})

By default, all documents that meet the conditions will be deleted. You can set the parameter {justOne:true}, and only the first document that meets the conditions will be deleted

Delete collection

db.collection.remove only deletes all documents. It is inefficient to directly use remove to delete all documents. You can use drop to delete the collection before re creating the collection and index

db.collection.drop( { writeConcern:<doc>})

Defines the security write level of this delete collection operation. This instruction not only deletes all documents in the collection, but also deletes the index of the collection

Tags: Java Back-end Distribution

Posted on Tue, 30 Nov 2021 22:56:32 -0500 by sugarat