NoSQL note.04

MongoDB installation and deployment

Deploy MongoDB service based on windows platform

  1. Download, unzip and install
  2. Start using configuration file
  3. Set variable
  4. 。。。

Database operation

  • View database
 > show dbs/databases
  • Create database
 > use myDB
 switched to db myDB

Note: If the database does not exist, create the database. Otherwise switch to the database

  • Statistics database information
 > db.stats()
  • Delete database
 > db.dropDatabase()  //删除当前数据库
 {
   
   "ok" : 1}
 > show dbs
admin  0.000GB
Config  0.000GB
local  0.000GB  //注:删除当前数据库,默认删除test数据库

Collection operation

  • Create collection
//语法:
> db.createCollection(name,{
capped:<Boolean>,autolndexld:<Boolean>,size:<number>,max:<number>
})

name: collection name
capped: whether to enable the collection limit, the default is not
size: the space used by the collection is limited, the default is not
max: the maximum number of items in the collection is limited, the default is not (priority is less than max)
autolndexld: whether to use _id as an index, the default use

  • View collection
> show collections
> db.getCollectionInfos()
  • Rename collection
> db.myCollection(原名称).renameCollection("myColl(新名称)")
{ "ok" : 1 }
  • Delete collection
> db.myColl.drop()  //db.集合名称.drop
true  // 执行成功
  • Fixed-length collection
> db.createCollection(name, {capped: <Boolean>, 
autoIndexId: <Boolean>, 
size: <number>, max <number>} )

capped: Whether fixed length, true is fixed length
size: the size of the number of documents in the collection (in bytes)
Max: Specify the maximum number of documents allowed in the collection

> db.myCollection.isCapped()                //判断集合是否定长。

The capacity in the fixed-length collection is recycled for real-time monitoring

Document operation

  • Insert
> db.collection_name.insert ({
   
   "":"", .. , ,})   //一次性插入一条文档的命令。
> db.collection_name.insertMany([{},{},..])  //一次性插入多条文档的命令。

> db.mydb.insert({
   
   "x":"10"})  //不指定_id的值,自动创建
WriteResult({ "nInserted" : 1 })
> db.mydb.insert({
   
   "_id":"user001","y":"10"})  //指定_id的值,取指定值
WriteResult({ "nInserted" : 1 })

> db.mydb.find()  //上面两条命令区别
{ "_id" : ObjectId("5c5ff402eb5725b5d8961b45"), "x" : "10" }
{ "_id" : "user001", "y" : "10" }
  • 删除(deleteMany/remove)
> db.collection_name.remove({匹配条件})
> db.collertion_name.deleteMany({匹配条件})
  • Update

When some memory errors or some content changes, you need to update the database file

Update a single document: atomicity .

Update multiple documents: each document is atomic, but the entire update operation is not atomic . There are cases where the previous document is updated successfully and the subsequent update fails.

Update the same document at the same time: You need to wait, and the result is determined by the later update operation.

Update method: update, save

save()
replaces the existing document by passing in the document, and the _id is updated if it exists, and if not

> db.mycoll.save({ "_id" : ObjectId("**"),"":"",..})
//替换_id为**的文档数据 

update() is
used to update existing documents

>db.col.update(<query>,<update>,
	{
	upsert:<boolean>,
	multi:<boolean>,
	writeConcern:<document>
	})

<query > : update query conditions
<update > : update objects and some update operators (such as: $inc... etc.)
upsert : if there is no update record, whether to insert objNew, the default is false, not insert
multi : the default is false, only update the first
piece of data found, if set to true, multiple pieces of data can be found according to the conditions and all updated writeConcern : optional, the level of the exception thrown

> db.colname.update({匹配字符},{修改器(如:$inc..):{
   
   key:value}},{选项})
// 例:修改多条数据,同时把多个"name":"zs"的“age”改为20(第二个设为true)
> db.myColl.update({
   
   "name":"zs"},{$set:{
   
   "age":20}},false,true)
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })

Modifier:
(1) $inc (modify the value, do addition, only for numeric types)
(2) $mul (modify the value, do multiplication)
(3) $set (complete the modification of specific requirements, that is, modify a certain value .If the specified key does not exist, the add operation is performed)
(4) $push (array insert, insert at the end of the document, if the key does not exist, add the key-value pair of the array type at the end of the document )
(5) $addToSet ( add elements to the array, if there is not added)
(. 7) $ the unset (delete field)
(. 6) $ min (compared to the current value of a given document field value, when a given value comparison small , the current document is modified The value is the given value
)
(7) $max (The given value is compared with the current document field value, when the given value is relatively large , the current document value is modified to the given value)

summary

Tab key completion (the front of the tab may have been wrong)
formatted input: you can enter after you have not finished typing , and then
finally exit: quit()

Database related operations

Create: use, statistics: stats(), delete: dropDatabase()

> use test
switched to db test
> db.stats()
{
        **//相关信息
        "ok" : 1
}

Collection related operations

Create: createCollection,
view: show collections,
display: getCollectionInfos(),
rename: renameCollection,
delete: drop()

> db.createCollection("mycollection")
{ "ok" : 1 }
> show collections
mycollection
> db.getCollectionInfos()
[
        {
                "name" : "myCollection",
                "type" : "collection",
                "options" : {

                },
                "info" : {
                        ** //相关信息
]
> db.mycollection.renameCollection("mycoll")
{ "ok" : 1 }
> db.mycoll.drop()
true

Document related operations

Add documents: insert and insertMany
Delete documents: remove and deleteMany
Update documents: save and
update
(modifiers: inc, set, push, addToSet, mul, rename, unset, min, max)

//insert 和 insertMany  添加
> db.myColl.insert({
   
   "name":"zhangsan",age:18,gender:"male"})  //添加数据
WriteResult({ "nInserted" : 1 })  //成功
> db.mycoll.find().pretty()
{
        "_id" : ObjectId("60**a0"),
        "name" : "zs",
        "age" : 10,
        "gender" : "male"
}
> db.mycoll.insertMany([{
   
   "name":"lisi","age":18,"gender":"male"},{
   
   "name":"zs","age":19,"gender":"male"},{
   
   "name":"ww","age":19,"gender":"female"}])  //添加多条数据
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("**"),
                ObjectId("**"),
                ObjectId("**")
        ]
}  // 成功
//remove 和 deleteMany  删除
> db.mycoll.remove({
   
   "name":"lisi"})  // 删除“name”为“lisi”的文档
WriteResult({ "nRemoved" : 1 })
> db.mycoll.deleteMany({
   
   "age":19})  //删除所有“age”为19的文档
{ "acknowledged" : true, "deletedCount" : 2 }
//save 更新
> db.myColl.save({
   
   "_id" : ObjectId("60**a0"),"name":"zsf"})  //通过_id更新修改
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
//update 更新
> db.mycoll.insert({
   
   "name":"zs","userId":"user001","age":18,"gender":"male"})
WriteResult({ "nInserted" : 1 })  //原数据添加

> db.mycoll.update({
   
   "name":"zs"},{$inc:{
   
   "age":1}})  // $inc示例,实现age+1
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.myColl.update({
   
   "name":"zhangsan1"},{$mul:{
   
   "age":2}})  //$mul示例,实现age*2
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.mycoll.update({
   
   "name":"zs"},{$set:{
   
   "age":20}})  //用 $set 修改
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.mycoll.update({
   
   "name":"zs"},{$set:{
   
   "email":["[email protected]"]}})  //用 $set 添加
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.mycoll.update({
   
   "name":"zs"},{$push:{
   
   "email":"[email protected]"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
/* email键存着一个数组,用 $push 完成插入,即:
  "email" : [
             "[email protected]",
             "[email protected]"
            ]
  重复 $push 将重复插入
*/

> db.mycoll.update({
   
   "name":"zs"},{$addToSet:{
   
   "email":"[email protected]"}})  //向email数组中添加, $addToSet 示例,已存在所以不改变
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 }) 

> db.mycoll.update({
   
   "name":"zs"},{$unset:{
   
   "email":[]}})  //用 $unset 删除字段
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.mycoll.update({
   
   "name":"zs"},{$min:{
   
   "age":18}})  //$min,age20→18
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.mycoll.update({
   
   "name":"zs"},{$max:{
   
   "age":20}})  //$max,age18→20
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Guess you like

Origin blog.csdn.net/weixin_47594116/article/details/114876848