1. Introduction to the database
SQL: Structured Query Language
2. Introduction to MongoDB
BSON: binary JSON
3. Set MongoDB as a system service
4. Basic operations of MongoDB
In MongoDB, neither database nor collection needs to be created manually. When we create a document, if the collection or database where the document is located does not exist, she will automatically create the database and collection!
-
basic instructions
-
show dbs: show all current databases
show database: Displays all current databases
-
use database name:Enterto the specified database (may not exist)
-
db: Indicates where we are currentlydatabase
-
show collections: show all the collections in our database
-
-
CRUD operations
-
Insert document into database
db..insert(doc): Insert a document into the collection
Insert a new student object into the stus collection in the test database
db.stus.insert({name: "Monkey King", age: 18, gender: "male"})
-
Query all documents in a collection
db..find()
-
5. Install the graphical tool
6. Insert the document
db.collection.insert()
- Insert one or more documents into a collection
- When we insert a document into the collection, if the _id attribute is not specified for the document, the database will automatically add
the _id attribute to the document, which is used as the unique identification of the document - _id can be specified by yourself. If we specify it, the database will not be added. If you specify _id by yourself, it must also ensure uniqueness
- db.collection.insertOne(): Insert a document object
- db.collection.insertMany(): Insert multiple document objects
db.stus.insert({
name:"冉海锋",age:28,gender:"男"})
db.stus.find()db.stus.insert([
{
name:"沙和尚",age:36,gender:"男"},
{
name:"白骨精",age:16,gender:"女"},
{
name:"蜘蛛精",age:14,gender:"女"}
])
-
$push: used to add a new element to the array
db.user.update({username:"tangseng"},{$push:{"hobby.movies":"Interstellar"}})
-
$addToSet: Adds a new element to the array (similar to adding to the set collection, if the element already exists in the array, the addition fails becausenot repeatable)
db.user.update({ username:"tangseng"},{ $addToSet:{ "hobby.movies":"Interstellar"}})
7. Querying documents
db.collection.find()
-
find() is used to query all eligible documents in the collection
-
find() can receive an object as a condition parameter
- { }: means all documents
- {property:value}: The query property is a document with the specified value
- The return value is aarray
-
db.collection.findOne()
-
Used to query the first document in the collection that matches the criteria
-
returns a document
-
-
db.stus.find({}).count(): Query the number of all results
db.stus.find({
name:"冉海锋"})
db.stus.findOne({
name:"冉海锋"})
db.stus.find({
name:"冉海锋"})[0]
db.stus.find({
}).length()
8. Modify the document
- db.collection.update(query condition, new object)
- update() will by default use the new object toreplaceold object
- update() will only modify one object by default
If you need to modify the specified attribute, instead of replacing, you need to use the "modification operator" to complete the modification
- $set: can be used to modify the specified property in the document
- $unset: Can be used to delete the specified attribute of the document
db.collection.updateMany(): Modify multiple eligible documents at the same time
db.collection.updateOne(): Modify a qualifying document
db.collection.replaceOne(): replace a qualifying document
-
The attribute value of a MongoDB document can also be a document. When the attribute value of a document is a document, we call this document an embedded document.
-
MongoDB supports querying directly through the properties of embedded documents. If you want to query embedded documents, you can use ==.form to match, and the attribute name must useQuotes ==, double quotes and single quotes can be
db.user.find("hobby.movies":"hero");
db.stus.find()
db.stus.update(
{
name:"沙和尚"},{
age:28}
)
db.stus.update(
{
"_id" : ObjectId("5f86edc1048d21081bd45f3b")},
{
$set:{
gender:"男", address:"流沙河" }} )
db.stus.update(
{
"_id" : ObjectId("5f86edc1048d21081bd45f3b")},
{
$unset:{
address:"流沙河" }} )
db.stus.updateMany(
{
"name" :"冉海锋"},
{
$set:{
address:"高老庄" }} )
db.stus.find()
db.stus.update(
{
"name" :"冉海锋"},
{
$set:{
address:"呵呵呵" } },
{
multi:true } )
db.stus.find()
9. Delete documents
- db.collection.remove()
- You can delete documents based on conditions, passing conditions in the same way as find()
- Can delete all documents that meet the conditions, delete multiple by default
- ifsecond parameterpass atrue, then only one
- If only one { } is passed as a parameter, all documents in the collection will be removed
- db.collection.deleteOne()
- db.collection.deleteMany()
- db.collection.drop(): drop the collection (if the last collection is gone, the database is gone...)
db.stus.remove({
age:28},true)
db.stus.remove({
}) //性能差
db.stus.drop()
db.dropDatabase()
- Generally, the data in the database will not be deleted, so the delete method is rarely called. Generally, a field is added to the data to indicate whether the data is deleted.
10. Practice
//添加两万条数据的性能高,尽量少调用系统的方法
var arr=[];
for(var i=1;i<=20000;i++){
arr.push({
num:i});
}
db.user.insert(arr);
//查询numbers中num大于5000的文档
db.unmbers.find({
num:{
$gt:500}})
//查询numbers中num小于30的文档
db.unmbers.find({
num:{
$lt:500}})
//查询numbers中num大于40小于50的文档
db.numbers.find({
num:{
$gt:40,$lt:50}})
//查询numbers前10条的数据
db.numbers.find({
num:{
$lte:10}})
//limit()设置显示数据的上限
db.numbers.find().limit(10)
//查询numbers中第11条到20条的数据
//skip()用于跳过指定数量的数据 skip( (页码-1)*每页显示的条数 ).limit(每页显示的条数)
//MongoDB会自动调整limit()和skip()的位置
db.numbers.find().skip(10).limit(10)
db.numbers.find().limit(10).skip(10)
11. Relationships between documents
-
one to one
-
couple
-
In MongoDB, this can be done viaembedded documentin the form of a one-to-one relationship
db.WifeAndHusband.insert([ { wife:"黄蓉", husband:{ name:"郭靖" } }, { wife:"潘金莲", husband:{ name:"武大郎" } } ])
-
-
one to many / many to one
-
One-to-many: parents and children, users and orders, articles and comments, also viaembedded documentway to map a one-to-many relationship (set the attribute of 1 to the field in the many)
db.order.insert({ list:["watermelor"], user_id:ObjectId("5f87b1deda684b252c2fc7a5") }) var user_id = db.users.findOne({ username:"swk"})._id //查询孙悟空的订单 db.order.find({ user_id:user_id})
-
-
many to many: categories and items, viaembedded documentThe way
db.teacher.insert([ {name:"洪七公"}, {name:"黄药师"}, {name:"龟仙人"} ]) db.stus.insert([ { name:"郭靖", tech_ids:[ ObjectId("5f87b4b6da684b252c2fc7a8"), ObjectId("5f87b4b6da684b252c2fc7a9") ] }, { name:"孙悟空", tech_ids:[ ObjectId("5f87b4b6da684b252c2fc7a8"), ObjectId("5f87b4b6da684b252c2fc7a9"), ObjectId("5f87b4b6da684b252c2fc7aa") ] } ])
12. Practice
//查询工资小于1000或者大于2000的员工
db.emp.find( $or:[ {
sal:{
$lt:1000}},{
sal:{
$gt:2500}} ])
//为所有工资小于1000的增加400
db.emp.find({
sal:{
$lte:1000}}, {
$inc:{
$sal:400}})
13. sort and projection
-
When find() queries documents, the default is to sort in ascending order according to the value of _id
-
sort() can be used to specify the sorting rules of documents, need to pass aAttributesTo specify the collation, 1 means ascending order, -1 means descending order
db.users.find({ }).sort({ sale:1}) db.users.find({ }).sort({ sale:1,qq:1}) //先指定sale的升序 再qq的降序
-
limit, skip, sort can be called in any order
-
When querying, we can set the position of the second parameterProjection of query results
db.users.find({ },{ sale:1})