Home>

Please download the original file on my github:https://github.com/yangqingxian/mongodb

Here are a few things:

This is the third time this article has been modified.This is also the first time that GitHub is used to control the version in the true sense.Think about it a little bit excited :)

2. The content structure is consistent with the basic mongodb commands.Just adding a lot of content into it,For those who want to learn more about mongodb database

3. I am actually a novice,So I will explain the content in very plain language,If you are like me,Then two birds fly together

4.The following content is my excerpt from "Mongodb Big Data Authoritative Guide (2nd Edition)"

5. The command examples in it have not created the database and collection in advance, they are written temporarily when they are needed.Pay attention to understanding

The comparison between mongodb database structure and traditional relational database,Easy to understand next

Database->Collection->Document

Database->table->column

-------------------- Database content ------------------

View all databases

show dbs

Delete database

db.dropdatebase ()

-------------------- Collection content --------------------

Create collection

db.createcollection ()

View all collections \ tables

show collections
show tables

Select a collection

use db_name

View collection information

db.stats ()

Delete a collection,But you need to specify a database first,That is, first use db_name

db.dropdatabase ()

Modify the name of the collection

db.collection_name.renamecollection ("new_name")

---------------------- Document Contents ----------

Insert data

db.collection_name.insert (document)
db.collection_name.save (document)

Query data multiple data

db.collection_name.find ()

You can specify what to return

Parameter explanation

db.collection_name.find (
{query_term:value},return_key_name:1}
)

The first parameter of a find () function is the query condition.That is, documents that match the content will be filtered out,If there are no query conditions,Then enter {}, cannot be empty

The second parameter of the b find () function is to specify what is returned,For example, a Xiaoming document in a collection of students contains multiple pieces of content.Name, student number, home address, etc.Now I just want to see the name,When you do n’t want to query, return the entire content of the xiaoming document.You can use this form of "keyname:1", the following 1 means to filter out the content and output in positive order0 means filter out the rest of the content,-1 means that the reverse order is the same as 1.

c can return multiple records,Here is just an example,Take the example of ixaoming

{
"name":1,"student_id":1
}

This returns two messages,A name, a student_id

2. Query nested information

Understanding the following information in combination with a two-dimensional array

{
"name":"yang","sex":"man","skill":[
{"php":1},{"mongodb":4},{"redis":5}
],"favorite_food":"meat"
}

Among them, if you use skill as the query condition of find (),Don't write it like this

--- Error example ---

db.self.find ({"skill":[{"php":1}]})

This is impossible to find.Because in this way mongodb will parse {"skill":[{"php":1}]} into the skill array containing only "php":1.The above example obviously does not meet this requirement,So can't find

--- Correct example ---

db.self.find ({"skill.php":1})

Used here. Tell the mongodb database to match the content of php in the skill array to 1. The focus is on whether there is a record of "php":1

--- Correct example 2 ---

If you must query the data using the error example above,You can use the $elemmatch parameter, note where this parameter is used

db.self.find ({
"skill":{$elemmatch:
{"php":1}
}
})

Here $elemmatch is used as a conditional operator

Query a single piece of data

db.collection_name.findone ()

skip skips the initial number of queries,limit, limit the number of returns,sort, when x:1 indicates positive order,x:-1 means reverse order

db.collection_name.find (). skip (number) .limit (number) .sort ((x:1))

Count the number of documents that match the query

db.collection_name.find (). count ()

The count () function ignores skip () or limit () functions by default. For example, assuming there are 4 documents in the student collection, the following three statements will show different results

db.student.find (). limit (1) .count () The result is 4, count ignores the condition of limit (1)

db.student.find (). limit (1) .count (true) The result is 1, and the parameter true is passed to count ()

Get the unique value of the result

db.collection_name.distinct ("key_name")

Is also a query function,It's just that he will show the query result as a unique value compared to find (),Instead of based on the original collection,The number of documents to display the results,Understand in conjunction with distinct in a relational database, for example,There is a book collection-books, with the book title under the collection,Author, publication date, etc.Note that an author may have written many books,Now I want to see how many authors are in the collection,If I search directly using the find () function above

db.books.find (
{},{"writer":1}
)

This will list all the authors,But many are duplicates,Because find () returns results based on the number of documents,And distinct () will filter the results,

Where the duplicates

db.books.distinct ("writer")

Group query results

db.collection_name.group ()
Parameter 1 key is grouped by this key Parameter 2 initial sets the variable,This variable will be output in the end,Note that this variable is defined for each group.A new group is recreated from the beginning Parameter 3 reduce a function,During document grouping,That is, once a document is grouped, it will be executed once.Pass in two parameters,One is the parameter representing initial, and the other is the document that is currently grouped.For easy understanding,Named out and doc respectively

Parameter 4 keyf, optional, the same function as key, but you can specify a function to create a field that does not exist in the document as a basis for groupingNeed to pass a parameter of the current document

Parameter 5 cond filter,Only documents that meet this condition can participate in grouping

Parameter 6 finalize function to be executed after grouping is completed,Pass in the parameters representing initial

Let ’s take a look at an example to get a rough idea.First pass a few documents to the orders collection

data1={
 "_id":objectid ("552a330e05c27486b9b9b650"), "_class":"com.mongo.model.orders", "onumber":"002", "date":isodate ("2014-01-03t16:03:00z"), "cname":"zcy", "item":{
  "quantity":1,  "price":4.0,  "pnumber":"p002"
 }
}
data2={
 "_id":objectid ("552a331d05c275d8590a550d"), "_class":"com.mongo.model.orders", "onumber":"003", "date":isodate ("2014-01-04t16:03:00z"), "cname":"zcy", "item":{
  "quantity":10,  "price":2.0,  "pnumber":"p001"
 }
}
data3={
 "_id":objectid ("552a333105c2f28194045a72"), "_class":"com.mongo.model.orders", "onumber":"003", "date":isodate ("2014-01-04t16:03:00z"), "cname":"zcy", "item":{
  "quantity":30,  "price":4.0,  "pnumber":"p002"
 }
}
data4={
 "_id":objectid ("552a333f05c2b62c01cff50e"), "_class":"com.mongo.model.orders", "onumber":"004", "date":isodate ("2014-01-05t16:03:00z"), "cname":"zcy", "item":{
  "quantity":5,  "price":4.0,  "pnumber":"p002"
 }
}
db.orders.insert (data1)
db.orders.insert (data2)
db.orders.insert (data3)
db.orders.insert (data4)

Next showgroup () Function

example 1

db.orders.group ({
key:{data:1, "item.pnumber":1},initial:{"total":0},reduce:function (doc, out) {
out.total +=doc.item.quantity
}
})

The first is to group by the pnumber in the data and ietm arrays

Then define the output variable total to record the total number of each product

Next is to define the processing function,Which is the function in reduce,Note the order of the incoming parameters,The first parameter indicates the document that is currently grouped,The second parameter indicates initial, so doc can directly call doc.item.quantity, which is the content of the document.out can call out.total, the content of initial

Example 2

db.orders.group ({
keyf:function (doc) {
return {"month":doc.date.getmonth () + 1};
},initial:{"total":0, "money":0},reduce:function (doc, out) {
out.total +=doc.item.quantity * doc.item.price
},finalize:function (out) {
out.avg=out.money/out.total;
return out;
}
})

First of all, this example shows the use of keyf. He returns a new field-month. Next, mongodb will classify according to the calculation result of month.

Next, there are incoming parameters in the keyf and finalize functions.In fact, this parameter has nothing to do with the parameter name in reduce.It is written here mainly to understand the meaning

Finally, a variable avg is temporarily created in finalize. This avg will also be output at the end.

the last point,The results processed in the function will be returned

---------------- Use conditional operators to filter query results ------------------

Generally used inside the first parameter of find (),Used as a filter

--- $gt, $lt, $get, $lte, $ne ---

db.collection_name.find (
{
key_name:{$gt:value}
})

Note the position of the operator,See examples to make it easier to understand

db.student.find (
{
"height":{$gt:180}
})

Means to select students whose height is higher than 180 in the student set

You can use both operators to specify a range

db.student.find ({
"height":{$gt:180, $lt:220}
})

The use of these two is the same as above,But you need to talk about it separately,Because it's a bit special

--- $in, $nin ---

db.student.find ({
"height":{$in:[170,180,190,200]}
})

Indicates that students with a height of 170, 180, 190, 200 are selected, and $nin is used to select students other than 170, 180, 190, 200.

--- $all ---

The content of the above $in is "or", as long as your height is 170, or 180, or 190, or 200, then you meet the filter criteria,$All is a relationship

db.student.find ({
"height":{$all:[170,180,190,200]}
})

This sentence means that your height is 170, 180, 190, and 200 to meet the condition.

--- $or ---

db.student.find ({
$or:[
{"score":100},{"sex":man}
]
})

In the example above,The relationship between score:100 and sex:man is "OR". The following example shows the effect of $or.

db.student.find (
{"score":100, "sex":"man"}
)

The relationship between score:100 and sex:man is

limit (x) Function plusskip (y) function =$slice:[y, x]

The specific use method can be seen in the following example

db.student.find (
{},{"height":{$slice:[10,5]}}
)

Still the old saying,Pay attention to the position of $slice. This sentence means to screen the 11th to 15th height people. The first parameter is the parameter of skip () and the second is limit ()

limit () Thefunction limits the number of documents returned.$size is to filter the array of matching numbers,See the following example to understand

First add the following information to the database

message={
"cds":[
{"first_song":"hello"},{"second_song":"world"},{"third_song":"again"}
]
}
db.songs.insert (message)

Then let's query the above results

db.songs.find (
{"cds":{$size:2}}
)

No results are returned.Because there are 3 sets of data in the cds array

db.songs.find (
{"cds":{$size:3}}
)

Returns all results,Pay attention,Here is passed as the first parameter of the find () function,So it ’s the filter

Filter values ​​with specific fields

db.collection_name.find (
{
key_name:{$exit:true}
})

Returns the document in which the field exists,Note that this field exists here,Without specifying the content of the field

Filter return results based on data type

db.collection_name.find (
{
"key_name":{$type:x}
})

There are many values ​​of x,Not introduced here,Because it ’s too much to read it

Use regular expressions in filtering

db.collection_name.find (
{
"key_name"://
})

Add the contents of the regular expression in //

update data

db.collection_name.update ({original_key:original_value}, {new_key:new_value})

1.As long as the original collection contains original_key:original_value, it will be selected as the operation object

2. The entire collection will be updated to new_key:new_value instead of just updating original_key:original_value

Compared to the above, which updates the entire collection,Added the form of $set:to update only some fields

db.collection_name.update ({original_key:original_value}, {$set:{new_key:new_value}})

A field was updated with $set above,You can delete a field using $unset

db.collection_name.update {
{},{$unset:{key:value}}
}

Create this piece of data if this update does not exist,Add the third parameter to true.

db.collection_name.update ({original_key:original_value}, {new_key:new_value}, true)

Or the following form

db.collection_name.update ({original_key:original_value}, {new_key:new_value}, {upsert:true})

update will only update the first record that meets the conditions,But when i want to update multiple records,Set the third parameter to false, the fourth parameter to true, and also set $set

db.collection_name.update ({original_key:original_value}, {$set {new_key:new_value}}, false, true)

------------------ Insert data-array part --------------------

Insert data

db.collection_name.update (
{original_key:value},{$push:{
new_key:new:value
}}
)

Note that if original_key does not exist, it will be created,And defined as an array,new_key:value is the first value

If original_key exists and the number array,Insert new_key:value, if not an array,Error

Insert multiple values ​​at once,The previous is using $push to insert one value at a time,If i want to insert multiple values,Need to use the following

db.collection_name.update (
{original_key:value},{$push:{
new_key:{
$each:[
"value1","value2","value3"
]
}
}
})

Note that $push here is for array operations,That is, the content after $each will be added to the array of new_key

Corresponds to $push, $pop deletes the data in the array

db.collection_name.update (
{original_key:value},{$pop:{
{original_key:1}
}
})

Note that 1 here means the number of deletions,It can be an integer of 2, 3, etc., which means that deletion starts from the back end of the array,Can also be a negative number such as -1, which means deleting from the front of the array

The preceding $pop can specify the number of deletions,But you cannot specify the conditions for deletion.$pull can

db.collection_name.update (
{original_key:value},{$pull:
{key1:value1}
}
)

$pull will delete all the value1 data in key1. Note that the value1 data in key1 is deleted, not key1, so as long as the key1 array contains value1, value1 will be deleted.

Similar to $pull, $pullall can delete multiple data

db.collection_name.update (
{original_key:value},{$pullall:{
key1:
[
"value1","value2","value3"
]
}
})

$addtoset is a very useful command to add data to an array.Add if the data does not exist,If it exists, it will not be added repeatedly.

db.collection_name.update (
{original_key:value},{$addtoset:{
new_key:{
$each:[
"value1","value2","value3"
]
}
}
})

Imagine,If you do not add $each here, if you do not add $each, it will become a new array directly added to the array new_key

["value1", "value2", "value3"]

You can tryUnderstand the function of $each, return to $addtoset, if value1, value2, value3 exist in the original array, it will not be added,If it doesn't exist,Then add nothing to it,Some will not be added repeatedly,They do not affect each other.

Atomic operation

This does not explain what is called atomic operation,For our users, we just need to know how to use atomic operations.

db.collection_name.findandmodify (
{
query:{key:value},sort:{key2:1/-1},update/remove:true,new:true
}
)

query specifies the document to query

sort sort, the meaning of 1, -1 is not explained here,Same as above

update/remove means operation

new means return the final modification result,Can be left blank

Delete all found data

db.coolection_name.remove ({key:value})

Delete a table

db.collection_name.drop ()

Viewing the Index of a Collection

db.collection_name.getindexes ()

Create index

db.collection_name.ensureindex ((key:value))

The previous is based onkey:value to create an index,Next, create an index for all the fields in a collection.

db.collection_name.ensureindex ({key:1})

The creation of a composite index is to add a few more contents to it

Delete index

db.collection_name.dropindex ((key:value))

Delete all indexes

db.collection_name.dropindexes ()

What we have operated before is a collection,Next we need to learn how to easily operate multiple collections.There are two ways,Manually or using dbref

Create two collections first

collection1={
"name":"yang","sex":"man"
}
collection2={
"id":1,"name":"yang","math":60,"pe":30,"chinese":60
}
db.student.save (collection2)
db.yang.save (collection)

Here is the general idea

yang=db.yang.findone ()
db.student.find (
{"name":yang.name}
)

mongodb does not support multi-table operations like traditional relational databases,mongodb all need to save the data first,Called again,As the above yang saves what is needed for find () query,Need to read the data from the database and save it before calling it.Where yang.name is equal to "yang"

The next step is to use dbref to reference the database.Calling dbref requires three parameters,The first call to collection_name, id, db_name, this is optional,Still the example above,Next use the dbref method, I can't figure this out

  • Previous Detailed Vue animation events and examples of transition animations
  • Next Vue command v-for traversal output of JavaScript arrays and json objects summary
  • Trends