MongoDB database operation

1, MongoDB database operation

1. Create database

use The command means to switch the database. If the database does not exist, the database will be created.
use Database name

2. Display database

adopt show dbs or show databases view the database

be careful

1.Different roles see different databases. Administrators see all databases, and ordinary users can only see their own databases
2.When there is no data in the new database, the show dbs or show databases Cannot be viewed. You need to add one to the database document(db.test.insert({"key":"value","key2":"value2"})),To see

3. Delete database

To delete a database, you need to switch to the database to be deleted, and the login user has dbAdminAnyDatabase Permissions, executing db.dropDatabase(). 

use test
db.dropDatabase()

2, MongoDB collection operation

1. Create collection

A set in MongoDB is a set of documents, which is equivalent to a table in a relational database.
MongoDB uses dB Use the createcollection() function to create a collection
Syntax format: dB createCollection(name,options).
Name: name of the collection to be created
Options: optional parameter that specifies options for content size and index

MongoDB In fact, you do not need to explicitly create a collection when using
use test
db.table1.insert()
Can be created implicitly table1 aggregate

The command to create a collection of default options is as follows:

>db.createCollection("c1")
{"ok":1}
>db.c1.insert("a":"1")
>show tables
c1
>
# Mode 1:
db.c2.insert({"a":"1"}) # When the first document is inserted, the collection is created and contains the document
# Mode 2:
db.c3 # Create an empty collection. If there is no data in it, you can't view it through show tables or show collections. You need to insert a document into the collection to see it.

2. View collection

View all collections through show tables or show collections

> show tables;
user
> db.c1.insert({"a":1})
WriteResult({ "nInserted" : 1 })
> show tables;
c1
user
> show collections
c1

Pass dB COLLECTION_ NAME. Stats() view collection details

>db.c3.stats()

3. Delete collection

Pass dB COLLECTION_ NAME. Drop() delete collection

> show collections
c1
user
> db.c1.drop()
true
> show collections
user
> 

3, Document operation

1. Insert document

1.1. Single insertion

You can insert a single document using insert/insertOne/save:

  • db.c1.insert({"name":"a"})
  • db.c1.insertOne({"name":"a"})
  • db.c1.save({"name":"a"})
1.1.1,insert

Pass dB COLLECTION_ NAME. Insert (document) inserts a document.
If not specified when inserting a document_ id defaults to the projectid type_ id cannot be repeated and cannot be changed after insertion

user1 = {
    "name":"zhangsan",
    "age":18,
    "hobbies":["music","read"],
    "addr":{
        "country":"China",
        "city":"BJ"
    }
}
db.user.insert(user1)

1.1.2,insertOne

After mongodb version 3.2, insertOne() function is provided to insert a single document

user2 = {
    "_id":"2",
    "name":"lisi",
    "age":20,
    "hobbies":["music","read"],
    "addr":{
        "country":"China",
        "city":"SH"
    }
}
db.user.insertOne(user2)

1.1.3,save

You can also insert a document using dB COLLECTION_ NAME. Save (document) command
If not specified_ The id field save() method is equivalent to the insert() method. If specified_ id field, it becomes the update document operation

user3 = {
    "_id":"3",
    "name":"wangwu",
    "age":22,
    "hobbies":["music","read"],
    "addr":{
        "country":"China",
        "city":"JS"
    }
}
db.user.save(user3)

1.2 batch insertion

You can insert multiple documents using insert/insertMany/save. The difference is that the object type {} of the function during single insertion is changed to the array type [{}, {}]:

  • db.c1.insert([{name:"a"},{name:"b"}])
  • db.c1.insertMany([{name:"a"},{name:"b"}])
  • db.c1.save([{name:"a"},{name:"b"}])
1.2.1 insert
user1 = {
    "_id":1,
    "name":"zhangsan",
    "age":22,
    "hobbies":["music","read"],
    "addr":{
        "country":"China",
        "city":"JS"
    }
}

user1 = {
    "_id":2,
    "name":"lisi",
    "age":22,
    "hobbies":["music","read"],
    "addr":{
        "country":"China",
        "city":"NJ"
    }
}
...
db.user.insert([user1,user2,user3,user4,...])
1.2.2 save
db.user.insertMany([user1,user2,user3,user4,...])
1.2.3 save
db.user.save([user1,user2,user3,user4,...])

2. Update document

2.1. update function

You can update the documents in the collection through the update series function or the save function. Let's take a closer look at the use of the update function.

The update() function is used to update existing documents. The syntax format is as follows:

db.COLLECTION_NAME.update(query,update,options)
  • Query: query condition of update, similar to where in SQL update statement
  • Update: the object of updte and some updated operators (such as $, Sinc...) can also be understood as the total set part of the SQL update statement
  • upsert: optional. If there is no update document, whether to insert it. true is insert, the default is false, no insert
  • multi: optional, whether to update in batch. true means that multiple records queried by criteria are all updated. False only updates the first record found. The default is false
user = {
    "name":"wangwu",
    "age":20,
    "hobbiess":["mucis","read"],
    "addr":{
        "country":"China",
        "city":"BJ"
    }
}

# Modify single article
db.user.updateOne({"name":"lisi"},user)
# If there are multiple matching data found, only the first one will be modified
db.user.update({"name":"lisi",user}) # Modifying a single entry is equivalent to updateOne()
# If there are multiple matching data found, modify all matching data
db.user.update({"name":"lisi"},{"$set":user},false,true) # Modify multiple
db.user.updateMany({"name":"lisi"},{"$set":user}) #  Modify multiple

Note: updating the document is the operation of the whole document. If the modified values are only name and age, except_ Attributes other than id will be deleted

2.2. Update operator

2.2.1, $set operator
# to update
db.user.update({"name":"zhangsan"},{$set:{age:18}},{multi:true})
2.2.2, $inc operator
# Age plus 5
db.user.update({"name":"wangwu"},{$inc:{age:5}})
2.2.3, $unset operator
# It is used to delete the key and leave the value of the key blank. When writing the command, the value of the field in $unset is arbitrary. No matter what value is given, it means deletion
db.user.update({name:"wangwu"},{$unset:{address:"at will"}})
2.2.4, $push operator
# Add an array element to the key of an array type in the document without filtering duplicate data. When adding, the key exists, and the key value type must be array; If the key does not exist, create a key of array type
db.user.update({},{$push:{hobby:"Write code"}},{multi:true})
2.2.5, $pop operator
# When deleting a data element, the desirable value can only be 1 or - 1. 1 indicates tail deletion, - 1 indicates header deletion
# Delete the first element in the hobby. Where the key in $pop is the array type attribute to be operated on
db.user.update({"name":"lisi"},{$pop:{hobby:-1}})
2.2.6, $pull operator
# Delete the elements that meet the conditions from the array, and delete them as long as the conditions are met
db.user.update({name:"wangwu"},{$pull:{hobby:"test"}})
2.2.7, $pullAll operator
# Multiple conditions can be set
db.user.update({name:"wangwu"},{$pull:{hobby:["test1","test2"]}})
2.2.8,$rename
# Rename the key. Any type of key can be renamed
db.user.update({name:"wangwu"},{$rename:{name:"username"}})

3. Delete document

3.1. MongoDB remove() function is used to remove data from the collection. Its syntax format is as follows:

db.user.remove(<query>,{justOne:<boolean>})
  • query: (optional) the condition of the deleted document
  • juistOne: (optional) if set to true, there is only one document. If False, deleting all matching data is equivalent to DB user. Deleteone(): deletes the first document that meets the criteria
    db.user.remove({"name":"lisi"},{justOne:true})
    db.user.deleteOne({"name":"lisi"})

3.2. Delete all data command:

db.user.remove({})
Equivalent to
Empty the set (table)
db.user.deleteMany({})

# Delete all embedded documents containing "country":"China"
db.user.deleteMany({"addr.country":"China"})
# Delete all documents with id greater than or equal to 3
db.user.deletemany({"_id":{"$gte":3}})
# Delete all
db.user.remove({})
db.user.deleteMany({})

Keywords: Spring

Added by supratwinturbo on Tue, 11 Jan 2022 02:40:53 +0200