Common operations of stud Mongodb

This article was first published on the blogger's public account LISTONE, welcome to pay attention!

Blogger public account

Introduction to Mongodb

Mongodb is a non-relational database (nosql).

MongoDB is a database based on distributed file storage. Written by C ++ language. Designed to provide scalable, high-performance data storage solutions for WEB applications. MongoDB is a product between relational and non-relational databases. It is the most feature-rich among non-relational databases and most like relational databases.

The following is a comparison of sql and mongodb terms:

SQL Mongodb
Table (Talbe) Collection
Row Document
Column (Col) Field
Primary Key Object ID (ObjectID)
Index Index
Nested table (Embeded Table) Embedded document (Embeded Document)
Array Array

MongoDB stores data as a document, and the data structure consists of key-value (key => value) pairs.

{"name": "listone", "age": 22}

There is a name key in the above document, and its value is the listoneage key value 22.

Take this document as an example to explain:

  • The key-value pairs in the document are ordered. If the key-value pairs of name and age are swapped in the above example, it will be regarded as a new document.
  • The value in the document is not limited to the string form, there are other more advanced types.
  • The key of the document uses UTF-8characters. Neutral is usually reserved, .and $it is reserved only when used in a specific environment _.

A collection is a collection of documents, which is different from a table in a relational database. And the collection is modeless, that is, different types of documents can coexist in the same collection:

{"name": "listone", "age": 22}
{"book": "The old man and the Sea"}

The above documents are two completely different documents. Since a collection can accommodate various types, why do we need multiple collections?
The significance of using multiple sets is:

  • Lower the entropy value. That is to reduce the degree of confusion.
  • Superiority in speed. Divide a particular type of document into multiple sub-collections to improve query efficiency.
  • A collection of documents of the same type exists to make the data more centralized.

Mongodb database operation

Create a database

use DATABASE_NAME

If the database does not exist, create the database, otherwise switch to the specified database.

  • View all databases
show dbs

Delete the database

db.dropDatabase()

Delete the current database, the default is test, you can use the db command to view the current database name.

Create collection

db.createCollection("listone")
  • View existing collections
show collections
show tables

Delete collection

db.collection.drop()

Replace collection in the command with the name of the collection to be deleted

Insert document

db.COLLECTION_NAME.insert(document)
db.COLLECTION_NAME.insertOne(document)
db.COLLECTION_NAME.insertMany(document_list)
  • Examples
>db.listone.insert({name:'listone',
	age:22
})
>db.listone.insertOne({name:'li',
	age:22
})
>db.listone.insertMany([
	{name:'stone',age:28},
	{name:'st',age:21}
])
>db.listone.find()
{ "_id" : ObjectId("5e7b83432e8c80cabc4a93c6"), "name" : "listone", "age" : 22 }
{ "_id" : ObjectId("5e7b85082e8c80cabc4a93c7"), "name" : "li", "age" : 22 }
{ "_id" : ObjectId("5e7b85592e8c80cabc4a93c8"), "name" : "stone", "age" : 28 }
{ "_id" : ObjectId("5e7b85592e8c80cabc4a93c9"), "name" : "st", "age" : 21 }

Query data

Query all data

db.getCollection('listone').find({})

Among them, {} contains the query conditions, because it is to query all the data, so just leave it blank, or omit {}.

Query specific data

db.getCollection('listone').find({"字段1":"固定值1","字段2":"固定值2"})

db.getCollection('listone').find({name:'listone'})

Query range value data

db.getCollection('listone').find(
	 {
        "字段1":{"操作符1":边界1,"操作符2":边界2},
     	"字段2":{"操作符1":边界1,"操作符2":边界2}
    }
)

db.getCollection('listone').find({age:{"$gt":22}})

Same as the previous method for querying specific data, except that the fixed value becomes a range ({"$ gt": 22} means greater than 22)

Operators and their meaning:

Operator significance
$gt Greater than
$gte Greater than equal
$lt Less than
$ lte Less than equal
$ ne Not equal

Limited return field

All the fields are returned in the previous example. Below we will filter some fields that are not needed.

db.getCollection('listone').find(用于过滤的条件,用于限定的条件)
  • Remove age
db.getCollection('listone').find({age:{"$gt":22}},{"age":0})

  • Only return age
db.getCollection('listone').find({age:{"$gt":22}},{"age":1})

You will find that in the following conditions for qualification, if age is 1, then age and _id are returned , if age is 0, then _id and name are returned . Without considering _id, we can understand:

If a certain field is limited to 0, it means that the field is not returned (that is, the default other fields are 1), so other unqualified fields will be returned

If a certain field is limited to 1, it means that the field is returned (that is, the default other fields are 0), so other unqualified fields will not be returned

Decorate the return result

  • Number of data
db.getCollection('listone').find({}).count()
  • Limit the number of results returned
db.getCollection('test_data_1').find({}).limit(限制返回的数量)
  • Sort results
db.getCollection('test_data_1').find({}).sort({"字段名":-1或者1})

Where -1 is the reverse order and 1 is the positive order.

change the data

  • updateOne: only update the first data that meets the conditions
  • updateMany: update all eligible data

Update data using updateMany

db.getCollection('listone').updateMany(
    // 下面是查询条件
    { 
       "字段名1":"查找条件1","字段名2":"查找条件2"
     },
   // 进行修改
    {
        "$set":{"字段名":"新的数据","字段名":"新的数据"}
    } 
)

delete data

  • deleteOne
  • deleteMany
db.getCollection('listone').deleteMany(
    // 删除的条件
    {
        "字段名1":"值","字段名2":"值2"
    }
)

Data deduplication

db.getCollection('test_data_1').distinct(去重的字段名,去重的条件)

Examples:

db.getCollection('listone').distinct("name",{"age":{"$ne":22}})

This means that the name field is deduplicated under the condition that age is not equal to 22. The returned data is an array with non-duplicate data in the name field of the deduplicated table.

Published 3 original articles · Likes0 · Visits 4

Guess you like

Origin blog.csdn.net/cookieXSS/article/details/105475500