Mongo characteristics

  • Nosql database
  • A database for distributed file storage
  • C++ written, high performance
  • usingBSONDocument storage

Directing a concept

Locally, open the mongodb installation directorybin/mongodb.exe, mongodb terminal appears, we enter the command in the terminal

The database

Add/switch databases

> use "mongodbTest"
Copy the code

Output:

> switched to db mongodbTest
Copy the code

When the monodbTest database does not exist, mongodb automatically creates it

Show all mongodb databases

show dbs
Copy the code

Deleting a Database

>use mongodbTest
> db.dropDatabase();
Copy the code

Switch to the database you want to delete before deleting it

Output:

{ "dropped" : "mongodbTest", "ok" : 1 }
Copy the code

Set (table)

Create a collection (table)

 > db.createCollection("colle");
{ "ok" : 1 }
Copy the code

General expressions:

> db.createCollection(name, options)
Copy the code

Create capped Collection (table)

A capped set is a set of fixed size, and when it gets full, it overwrites the data that was first stored in it. Why use a capped set?

  • Higher performance
  • Higher throughputBecause it is a fixed size, the order of inserts is guaranteed, so historical queries do not require index sorting, without this index overhead, and capped collections have higher throughput
> db.createCollection("cappedSize",{size:6142800,max:10000,capped:true})
{ "ok" : 1 }
Copy the code

Explain the above example:

  • cappedSize: Set name
  • size: Fixed size of the collection in bytes, in this case 6142800B. If this size is exceeded, mongodb will overwrite earlier data
  • max: A collection can contain a maximum of 10000 documents
  • capped: Indicates whether it is a capped array. Default is false

View collections (tables)

> show collections
colle
Copy the code

In mongodb, you don’t need to create collections. When you insert a collection that doesn’t exist, the collection is created by default

View the documents in the collection

db.collecName.find(<query>)
Copy the code
  • <query>Yes Query condition

Without query, all documents of the collection are queried by default

> db.collecName.find() { "_id" : ObjectId("607ce52e81fa2aa6bc3cf6a1"), "item" : "notebook", "qty" : 50, "size" : {" h ": 8.5," w ": 11," uom ":" in "}, "status" : "P"} {" _id ": ObjectId (" 607 ce52e81fa2aa6bc3cf6a3"), "item" : "Planner", "qty" : 75, the "size" : {" h ": 22.85," w ": 30," uom ":" cm "}, "status" : "D"}Copy the code

The above query is equivalent to the SQL statement SELECT * FROM inventory pass query:

> db.inventory.find({status:"D"}) { "_id" : ObjectId("607ce52e81fa2aa6bc3cf6a3"), "item" : "planner", "qty" : 75, "size" : {" h ": 22.85," w ": 30," uom ":" cm "}, "status" : "D"}Copy the code

SELECT * FROM inventory WHERE status = “D” FROM inventory

> db.inventory.find({status:{$in:["A","D"]}}) { "_id" : ObjectId("607cecfdb180136a61da3a64"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" } { "_id" : ObjectId(" 607cecfDB180136A61DA3A65 "), "item" : "notebook", "qTY" : 50, "size" : {" H ": 8.5, "w" : 11, "uom" : "in" }, "status" : "A" } { "_id" : ObjectId("607cecfdb180136a61da3a66"), "item" : "paper", "qty" : 100, "size" : {" h ": 8.5," w ": 11," uom ":" in "}, "status" : "D"} {" _id ": ObjectId (" 607 cecfdb180136a61da3a67"), "item" : "Planner", "qty" : 75, the "size" : {" h ": 22.85," w ": 30," uom ":" cm "}, "status" : "D"} {" _id ": ObjectId(" 607CECfDB180136A61DA3A68 "), "item" : "Postcard "," QTY ": 45, "size" : {" H" : 10, "w" : 15.25, "Uom" : "cm" }, "status" : "A" }Copy the code
Using Llmit

Db.collectionname.find ().limit(NUMBER) is used to read the specified document, where NUMBER is a NUMBER

> db.orders.find()
{ "_id" : ObjectId("607e4620b180136a61da3a6e"), "cust_id" : "A123", "amount" : 500, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a6f"), "cust_id" : "A123", "amount" : 250, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a70"), "cust_id" : "B212", "amount" : 200, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a71"), "cust_id" : "A123", "amount" : 300, "status" : "D" }
> db.orders.find().limit(2)
{ "_id" : ObjectId("607e4620b180136a61da3a6e"), "cust_id" : "A123", "amount" : 500, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a6f"), "cust_id" : "A123", "amount" : 250, "status" : "A" }
Copy the code

Limit (2): Filter out the first two data in this set

Use the Skip

Db.collectionname.find ().skip(NUMBER) is used to skip the specified document reading

> db.orders.find()
{ "_id" : ObjectId("607e4620b180136a61da3a6e"), "cust_id" : "A123", "amount" : 500, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a6f"), "cust_id" : "A123", "amount" : 250, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a70"), "cust_id" : "B212", "amount" : 200, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a71"), "cust_id" : "A123", "amount" : 300, "status" : "D" }
> db.orders.find().skip(1)
{ "_id" : ObjectId("607e4620b180136a61da3a6f"), "cust_id" : "A123", "amount" : 250, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a70"), "cust_id" : "B212", "amount" : 200, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a71"), "cust_id" : "A123", "amount" : 300, "status" : "D" }
Copy the code

As you can see from the example above, we skipped the first document using skip(1)

Sort to view the collection

Sort ({KEY:n}), sort by KEY

  • n=1ascending
  • n=-1Descending order
> db.orders.find()
{ "_id" : ObjectId("607e4620b180136a61da3a6e"), "cust_id" : "A123", "amount" : 500, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a6f"), "cust_id" : "A123", "amount" : 250, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a70"), "cust_id" : "B212", "amount" : 200, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a71"), "cust_id" : "A123", "amount" : 300, "status" : "D" }
> db.orders.find().sort({"amount":1})
{ "_id" : ObjectId("607e4620b180136a61da3a70"), "cust_id" : "B212", "amount" : 200, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a6f"), "cust_id" : "A123", "amount" : 250, "status" : "A" }
{ "_id" : ObjectId("607e4620b180136a61da3a71"), "cust_id" : "A123", "amount" : 300, "status" : "D" }
{ "_id" : ObjectId("607e4620b180136a61da3a6e"), "cust_id" : "A123", "amount" : 500, "status" : "A" }
Copy the code

The db. The orders. The find (). Sort ({” amount “: 1}) our value for the amount in an ascending order More examples, reference: docs.mongoing.com/mongodb-cru…

Delete collection (table)

> db.colle.drop();
Copy the code

Delete the collection as: colle

Insert document (row) into collection

  • insert— Insert single or more data,Not recommended
> db.mongodbColleTest.insert({name:"arzhu"})
Copy the code

Insert data for the mongodbColleTest collection. If the mongodbColleTest collection doesn’t exist, mongodb will create it

  • insertOne— Insert a single piece of data, return the inserted data
> var doucument = {title:"doc",desc:" new data "}; > db.mongodbColleTest.insertOne(doucument)Copy the code
  • insertMany()— Insert multiple data, return the inserted data set
> const res = db.tableCopy.insertMany([{name:"1"},{name:2}])
> res
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("60790594eaf92c106aba6674"),
                ObjectId("60790594eaf92c106aba6675")
        ]
}
Copy the code

Insert single data, use insertOne(), insert multiple data, use insertMany()

Update document (line)

In mongodb we use update to update the required data

db.collectionsName.update(
    <query>,
    <update>,
    {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
    }
    )
Copy the code
  • Upsert: Specifies whether to insert objNew if no update record exists. True indicates that the update record is inserted. The default value is false and no update record is inserted.
  • Multi: mongodb only finds the first Query-compliant document by default. Change this configuration to update all Query-compliant documents
  • WriteConcern: The level of an exception thrown
  1. Let’s create a new databaseupdateTest
> use uodateTest
switched to db uodateTest
Copy the code
  1. Add two documents
> db.updateTest.insertMany([{name:"arzhu",value:1},{name:"arzhu",value:2}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("60794a012582410d8e7d8170"),
                ObjectId("60794a012582410d8e7d8171")
        ]
}
> db.updateTest.find()
{ "_id" : ObjectId("60794a012582410d8e7d8170"), "name" : "arzhu", "value" : 1 }
{ "_id" : ObjectId("60794a012582410d8e7d8171"), "name" : "arzhu", "value" : 2 }
>
Copy the code
  1. To change thename=arzhuThe document
> db.updateTest.update({name:"arzhu"},{$set:{value:"newValue"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Copy the code

Update ({name:”arzhu”}, $set:{value:”newValue”}})

  • {name:"arzhu"}The document with name=”arzhu” was selectedWe did not change the multi parameter, which defaults to false, meaning that the document whose name=’arzhu’ we changed only changed the first matching document, the other documents were not changed
  • {$set:{value:"newValue"}}$set was used to change the match{name:"arzhu"}Change the value of value to newValue
  1. Let’s look at the changed data
> db.updateTest.find()
{ "_id" : ObjectId("60794a012582410d8e7d8170"), "name" : "arzhu", "value" : "newValue" }
{ "_id" : ObjectId("60794a012582410d8e7d8171"), "name" : "arzhu", "value" : 2 }
>
Copy the code

5. Change the value of multi and try to change all documents that match name=arzhu

> db.updateTest.update({name:"arzhu"},{$set:{value:"3"}},{multi:true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
> db.updateTest.find()
{ "_id" : ObjectId("60794a012582410d8e7d8170"), "name" : "arzhu", "value" : "3" }
{ "_id" : ObjectId("60794a012582410d8e7d8171"), "name" : "arzhu", "value" : "3" }
Copy the code

Delete document (row)

  • deleteMany()Used to delete multiple documents (rows)
db.collectionName.deleteMany(<query>)
Copy the code
  • deleteOne()Use to delete a single compliant document
deleteMany()

DeleteMany () to delete all data in a collection, pass in an empty number: {}

> db.updateTest.find() { "_id" : ObjectId("60795fa92582410d8e7d8173"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" } { "_id" : ObjectId("60795fa92582410d8e7d8174"), "item" : "Notebook", "qty" : 50, "size" : {" h ": 8.5," w ": 11," uom ":" in "}, "status" : "P"} {" _id ": ObjectId(" 60795FA92582410D8e7D8175 "), "item" : "paper", "qTY" : 100, "size" : {" H ": 8.5, "w" : 11," Uom ": "in" }, "status" : "D" } { "_id" : ObjectId("60795fa92582410d8e7d8176"), "item" : "planner", "qty" : 75, "size" : {" h ": 22.85," w ": 30," uom ":" cm "}, "status" : "D"} {" _id ": ObjectId (" 60795 fa92582410d8e7d8177"), "item" : "It", the "qty" : 45, "size" : {" h ": 10," w ": 15.25," uom ":" cm "}, "status" : "A" } > db.updateTest.deleteMany({}) { "acknowledged" : true, "deletedCount" : 5 } >Copy the code

To delete a document, add a matching condition:

> db.inventory.deleteMany({status:"A"})
{ "acknowledged" : true, "deletedCount" : 2 }
Copy the code
deleteOne()

Use only to delete the first document that meets the criteria

> db.inventory.deleteOne({status:"D"}) { "acknowledged" : true, "deletedCount" : 1 } > db.inventory.find() { "_id" : ObjectId(" 607CE52e81FA2AA6BC3CF6A1 "), "item" : "notebook", "qTY" : 50, "size" : {" H ": 8.5, "w" : 11, "uom" : "in" }, "status" : "P" } { "_id" : ObjectId("607ce52e81fa2aa6bc3cf6a3"), "item" : "planner", "qty" : 75, "size" : {" h ": 22.85," w ": 30," uom ":" cm "}, "status" : "D"}Copy the code

The index

What is the index? It can be understood as an identification of some document

The role of indexes

Reduce the number of documents queried, improve query efficiency, if there is no index. It’s inefficient to query all the documents in the collection

Create indexes

db.collectionName.createIndex({KEY:n},{options})
Copy the code
  • KEY: Key to index
  • n:n=1Create indexes in ascending order,n=-1Create indexes in descending order,N = other KEYA named index is created

Options:

The image above is from the rookie tutorialwww.runoob.com/mongodb/mon…)

The text search

To perform a text search, you must have a text index, and there is only one text index per collection

The text index

  1. Insert a document
> db.textData.insertMany(
    [
        { _id: 1, name: "Java Hut", description: "Coffee and cakes" },
        { _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
        { _id: 3, name: "Coffee Shop", description: "Just coffee" },  
        { _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" }, 
        { _id: 5, name: "Java Shopping", description: "Indonesian goods" } 
    ]
)
{ "acknowledged" : true, "insertedIds" : [ 1, 2, 3, 4, 5 ] }
Copy the code
  1. Creating a text index
> db.textData.createIndex({name:"text",description:"text"})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
Copy the code

A text index is created for name and desciption

  1. The text search
> db.textData.find({$text:{$search:"java coffee shop"}})
{ "_id" : 3, "name" : "Coffee Shop", "description" : "Just coffee" }
{ "_id" : 1, "name" : "Java Hut", "description" : "Coffee and cakes" }
{ "_id" : 5, "name" : "Java Shopping", "description" : "Indonesian goods" }
Copy the code

Analyze what this code means

  • $textFilter documents that have a document index
  • $search:'java coffee shop': Queries the ‘Java ‘,’coffee’, and ‘shop’ fields, which will be indexed when documents with text indexes exist.

Note here for more examples of case-insensitive text searches:

  • Query with"just coffee"Field document
> db.textData.find({$text:{$search:"\"just coffee\""}})
{ "_id" : 3, "name" : "Coffee Shop", "description" : "Just coffee" }
Copy the code
  • Query for documents that contain “Java” but not “hut”

– to eliminate

> db.textData.find({$text:{$search:"java -hut"}})
{ "_id" : 5, "name" : "Java Shopping", "description" : "Indonesian goods" }
Copy the code

The aggregation

Aggregate operations take selected data, perform some operation, and return the result of the operation, often used for data processing

Polymerization pipe

The definition of a pipe is that the result of this operation can be passed to the next operation for example

  1. Let’s look at the data
> db.orders.insertMany([ ... { ... cust_id:"A123", ... amount:500, ... status:"A" ... }, ... { ... cust_id:"A123", ... amount:250, ... status:"A" ... }, ... { ... cust_id:"B212", ... amount:200, ... status:"A" ... }, ... { ... cust_id:"A123", ... amount:300, ... status:"D" ... }, ... ] ); { "acknowledged" : true, "insertedIds" : [ ObjectId("607e4620b180136a61da3a6e"), ObjectId("607e4620b180136a61da3a6f"), ObjectId("607e4620b180136a61da3a70"), ObjectId("607e4620b180136a61da3a71") ] }Copy the code
  1. Perform the aggregation operation to findStatus ="A", grouped by cuse_id
> const res = db.orders.aggregate([{$match:{status:"A"}},{$group:{_id:"$cust_id",total:{$sum:"$amount"}}}])
> res
{ "_id" : "A123", "total" : 750 }
{ "_id" : "B212", "total" : 200 }
Copy the code

So without further ado, this is a very common example, just look at the picture

Explain it sentence by sentence

  • {$match:{status:"A"}}: Filters documents where status = A
  • {$group:{_id:"$cust_id",total:{$sum:"$amout"}}}:
    g r o u p Is to group documents . The structure of the group is in parentheses : _ i d = c u s t _ i d . t o t a l The operator is used in Group is the grouping of documents, and the structure of the group is in parentheses :\_id = cust\_id, with the operator ‘used in total
    Sum ‘means, calculate the sum of amout

The operator

Pipe operator

  • $match: Selects documents that meet the requirements. Such as{$match:{status:"A"}}This represents filtering out the document data for status=A
  • $project: Modify document structure, name, delete, add, etc
  • ` `

Query operator

  • $in: contains this condition{status:{$in:["A","D"]}}Documents whose status is equal to A or D
  • $or:

Modify operator

  • $set: Modifies this value. Such as{$set:{value:"newValue"}}Change value to newValue

Comparison operator

  • $gt: Greater than a value, such as age:{$gt:70},age is greater than 70
  • $gte: Is greater than or equal to a value, such as age:{$gte:70},age is greater than or equal to 70
  • $lt: less than a value, such as age:{$lt:40},age is less than 40
  • $lte: is less than or equal to a value, for example,age :{$lte:90},age is less than or equal to 90

Expression operator

Operator commonly used in aggregate operations

The Node connected mongo

Reference: docs.mongodb.com/drivers/nod…

Create a connection

const {MongoClient} = require("mongodb"); const url = "mongodb://localhost:27017"; //mongodb defaults to port 27017 const dbName = "updateTest"; // Mongoetest const client = new MongoClient(url,{useUnifiedTopology:true}); // Create a new connection client.connect((err)=>{if(err){console.log(err); return; } console.log(" link successful "); const db = client.db(dbName); })Copy the code

To find the data

const {MongoClient} = require("mongodb"); const url = "mongodb://localhost:27017"; //mongodb defaults to port 27017 const dbName = "updateTest"; const client = new MongoClient(url,{useUnifiedTopology:true}); client.connect((err)=>{ if(err){ console.log(err); return; } console.log(" link successful "); const db = client.db(dbName); Db.collection ("inventory").find({}).toarray ((err,data)=>{if(err){console.log(err); return; } console.log(data); client.close(); Close the connection})})Copy the code

Insert data

const {MongoClient} = require("mongodb"); const url = "mongodb://localhost:27017"; //mongodb defaults to port 27017 const dbName = "updateTest"; const client = new MongoClient(url,{useUnifiedTopology:true}); client.connect((err)=>{ if(err){ console.log(err); return; } console.log(" link successful "); const db = client.db(dbName); Db.collection ("inventory"). InsertOne ({"item" : "arzhu", "qty" : 1, "size" : {"h" : 14, "w" : 21, "uom" : "cm" }},(err,res)=>{ if(err){ console.log(err); return; } console.log(" See the result: ",res); })})Copy the code

Delete the data

const {MongoClient} = require("mongodb"); const url = "mongodb://localhost:27017"; //mongodb defaults to port 27017 const dbName = "updateTest"; const client = new MongoClient(url,{useUnifiedTopology:true}); client.connect((err)=>{ if(err){ console.log(err); return; } console.log(" link successful "); const db = client.db(dbName); Db.collection ("inventory").deletemany ({item:"arzhu"},(err,res)=>{// Delete item="arzhu" if(err){console.log(err); return; } console.log(" See the result: ",res); })})Copy the code

Modify the data

const {MongoClient} = require("mongodb"); const url = "mongodb://localhost:27017"; //mongodb defaults to port 27017 const dbName = "updateTest"; const client = new MongoClient(url,{useUnifiedTopology:true}); client.connect((err)=>{ if(err){ console.log(err); return; } console.log(" link successful "); const db = client.db(dbName); $set qty=29; $set qty=29; UpdateMany DB.collection ("inventory"). UpdateOne ({item:"journal"},{$set:{qty:29}},(err,res)=>{if(err){ console.log(err); return; } console.log(" See the result: ",res); client.close(); })})Copy the code