Mongode revisits the road (1)

Time:2021-7-23

Starting mongodb with Windows Service

//Create directory
d: data/
    Conf -- > configuration file directory
        Mongod.conf -- > configuration file
    DB -- > database directory
    Log file directory
        Mongodb. Log -- > logging file

First, open the DOS window as an administrator

//Execute the following command
C:\WINDOWS\system32>mongod --dbpath "d:\data\db" --logpath "d:\data\log\mongodb.log" --serviceName "mongodb" --serviceDisplayName "mongodb" --install
//When a prompt appears, it means that it is OK
2018-03-29T12:59:58.707+0800 I CONTROL  [main] log file "d:\data\log\mongodb.log" exists; moved to "d:\data\log\mongodb.log.2018-03-29T04-59-58".

Start a net service

C:\WINDOWS\system32> net start mongodb
Mongodb service is starting
Mongodb service has been started successfully.


//If you want to stop
net stop mongodb

Connect to database

C:\WINDOWS\system32>mongo
MongoDB shell version v3.4.10
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.10
Server has startup warnings:
2018-03-29T13:00:05.275+0800 I CONTROL  [initandlisten]
2018-03-29T13:00:05.275+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2018-03-29T13:00:05.275+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2018-03-29T13:00:05.276+0800 I CONTROL  [initandlisten]
> 

//So the connection is successful

Now let’s get to the point

Create database

> show dbs;
admin  0.000GB
local  0.000GB
>
//The default is by two, these two databases do not act rashly oh

Create and delete databases

Create database

//Create myfirstdb database
> use myfirstdb
switched to db myfirstdb

//View the current database
> db
myfirstdb

//Note: the Mongo database we just created is not in the list of databases. To display it, we need to insert some data into the Mongo database.

> db.mytest1.insert({"name":"test"});
WriteResult({ "nInserted" : 1 })
//Check again
> show dbs
admin      0.000GB
local      0.000GB
myfirstdb  0.000GB

Delete database

//Delete the current database
> db.dropDatabase()
{ "dropped" : "myfirstdb", "ok" : 1 }
> show dbs
admin  0.000GB
local  0.000GB

Create collection

//Create a default collection
> use myfirst
switched to db myfirst
> db.createCollection('ctest');
{ "ok" : 1 }
> show collections
ctest

//Create a collection with parameters
>db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } )
{ "ok" : 1 }
>

//To create a collection, you can use the following method
db.createCollection(name, options)

The options parameter is configured as follows

field type describe
capped Boolean If true, a fixed collection is created. A fixed set is a set with a fixed size. When the maximum value is reached, it will automatically overwrite the oldest document. The size parameter must be specified when the value is true.
autoIndexID Boolean (optional) if true, automatically_ The ID field creates an index. The default is false.
size numerical value (optional) specifies a maximum value (in bytes) for the fixed set. If capped is true, this value must be specified
max numerical value Optional) specifies the maximum number of documents in the fixed collection.

Delete collection

> db
mytest
> db.mytest.insert({"name":"test"});
WriteResult({ "nInserted" : 1 })
//So we have a mytest set

> db.mytest1.insert({"name":"sss"});
WriteResult({ "nInserted" : 1 })


//View all collections
> show collections
mytest
mytest1


//Delete the specified collection
> db.mytest.drop()
True // returns true if the deletion is successful, otherwise it is false
> show collections
mytest1

Insert document

The data structure of the document is basically the same as that of JSON.

All data stored in the collection is in bson format.
MongoDBuseinsert()orsave()Method to insert a document into the collection

insert

>DB. Col. insert ({Title: 'mongodb tutorial',
... Description: 'mongodb is a NoSQL database',
... by: 'rookie tutorial',
...     url: 'http://www.runoob.com',
...     tags: ['mongodb', 'database', 'NoSQL'],
...     likes: 100
... });
WriteResult({ "nInserted" : 1 })

//In the above example, col is our collection name. If the collection is not in the database, mongodb will automatically create the collection and insert the document.


//Check it out
> db.col.find();
{ "_ ID ": objectid (" 5abccb518777294f765db58a ")," title ":" mongodb tutorial "," description ":" mongodb is a NoSQL database "," by ":" rookie tutorial "," URL ": http://www.runoob.com ", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }


//It could be
>Document = ({Title: 'mongodb tutorial',
... Description: 'mongodb is a NoSQL database',
... by: 'rookie tutorial',
...     url: 'http://www.runoob.com',
...     tags: ['mongodb', 'database', 'NoSQL'],
...     likes: 100
... });
{
        "Title": "mongodb tutorial,",
        "Description": "mongodb is a NoSQL database,",
        "By": "rookie tutorial,",
        "url" : "http://www.runoob.com",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
> db.col.insert(document)
WriteResult({ "nInserted" : 1 })
>

save

//The save method is actually similar to insert, DB. Col. save (document). If not specified_ ID is no different from insert_ ID, the data will be updated.

If you want more than one insert:

Mongode revisits the road (1)

Update data

mongodbUpdate data throughupdateandsave

update()

//Grammatical format
db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

*Query is the query condition
*Update the content to be updated
*Upsert optional: if there is no update record, whether to insert objnew. True is insert. The default is false and no insert
*Multi optional: the default is false. Only the first record found is updated. If this parameter is true, all the records found by conditions will be updated.
*Writeconcern throws an exception, optional
//Instance
>DB. Col. update ({"title": "mongodb tutorial"}, {$set: {"by": "ZJJ"})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col.find().pretty()                                   })
{
        "_id" : ObjectId("5abccb518777294f765db58a"),
        "Title": "I have modified the title.",
        "Description": "mongodb is a NoSQL database,",
        "By": "rookie tutorial,",
        "url" : "http://www.runoob.com",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("5abccbc48777294f765db58b"),
        "Title": "mongodb tutorial,",
        "Description": "mongodb is a NoSQL database,",
        "By": "ZJJ", // here has been modified, and only one change has been made
        "url" : "http://www.runoob.com",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("5abccf818777294f765db58c"),
        "Title": "mongodb tutorial,",
        "Description": "mongodb is a NoSQL database,",
        "By": "rookie tutorial,",
        "url" : "http://www.runoob.com",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
>

//If you want to update, it's not just one place
>DB. Col. update ({title ':'mongodb tutorial'}, {$set: {title ':'mongodb'}, {multi: true})

save()

Save is changed by passing in a new document

>db.col.save({
    "_ ID ": objectid (" 56064f89ade2f21f36b03136 ") // change the data whose ID is the value
    "title" : "MongoDB",
    "Description": "mongodb is a NoSQL database,",
    "by" : "Runoob",
    "url" : "http://www.runoob.com",
    "tags" : [
            "mongodb",
            "NoSQL"
    ],
    "likes" : 110
})
  • Other examples
//Update only the first record:
db.col.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } );


//Update all:
db.col.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true );

//Add only the first item:
db.col.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false );

Add in all:
db.col.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true );

//Update all:
db.col.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} },false,true );

//Update only the first record:
db.col.update( { "count" : { $gt : 10 } } , { $inc : { "count" : 1} },false,false );

Remove document

MongoDB remove()Function is used to remove data from a collection.

//Format

db.collection.remove(     
    <query>,     
    {       
        justOne: <boolean>,
        writeConcern: <document> 
    } 
)

*Query: (optional) the condition of the deleted document.
*Justone: (optional) if set to true or 1, only one document will be deleted.
*Writeconcern: (optional) the level of exception thrown.

//The default is to delete all
>DB. Col.remove ({"title": "mongodb tutorial"}))
WriteResult({ "nRemoved" : 2 })


//If you only want to delete the first matching data
>Db.col.remove ({"title": "mongodb tutorial"}, 1))


//If you want to delete all
> db.col.remove({});
WriteResult({ "nRemoved" : 1 })

To be continued~~