MongoDB tutorial (including installation common commands related concepts usage tips common operations etc.)

  • 2020-05-09 19:33:27
  • OfStack

1. Installation and configuration
 
MongoDB official download station is http: / / www mongodb. org/downloads, can go to download the latest installer above
 
Installation of Windows platform
 
● step 1: download MongoDB
      click the official download address at the top and download the Windows version

● step 2: set the MongoDB program to a directory
After downloading      , unzip to the custom folder, e.g. D:\mongodb\

● step 3: set the data file directory
      create db and logs folders (equivalent to bin) in D:\mongodb\ directory,
      then creates the mongodb.log log file in the logs folder

● step 4: start the MongoDB service as the Windows service


// Enter the cmd The console
D:/mongodb/bin>mongod.exe --logpath D:/mongodb/logs/mongodb.log --logappend
                          --dbpath D:/mongodb/db
                          --directoryperdb
                          --serviceName MongoDB
                          --install
--directoryperdb Specify each DB Will the new 1 A directory

Once the installation is complete, you can start and stop MongoDB with the net start MongoDB and net stop MongoDB commands from cmd
 
● step 5: client connection verification
      open cmd and type: D:/mongodb/bin > mongo.exe

D:/mongodb/bin>mongo.exe
MongoDB shell version: 2.4.8
connecting to: test
>

 
Installation of Linux platform
 
● step 1: download MongoDB
      click the official download address above and download the Linux version

● step 2: set up the MongoDB program directory
Once the       download is complete, unzip it to the custom folder, e.g. /usr/local/mongo

● step 3: set the data file directory
      create the /data/db and /data/logs folders, and then create the mongodb.log log files in the logs folder

● step 4: start the MongoDB service and start it randomly as the Linux service


vi /etc/rc.local // use vi The editor opens the configuration file and adds the following 1 Lines of code
 
/usr/local/mongo/bin/mongod --dbpath=/data/db/ --logpath=/data/logs/mongodb.log --logappend& 

When the installation is complete, you can finish with pkill mongod
 
2. Logical structure of data
 
● MongoDB document (document), equivalent to one row in a relational database.
● multiple documents make up a collection (collection), which is equivalent to a table in a relational database.
● multiple collections (collection), logically organized from 1, is the database (database).
● multiple databases are supported for one instance of MongoDB (database).
● default port: 27017
 
3. Common commands
 
Select database
use persons

Display current database
db  ||  db.getName()

Delete current database
db.dropDatabase()

Displays the collection Collections under the current database

show tables || show collections

Displays the current system.profile

show profile

Displays the user Users under the current database

show users

Add user

db.addUser(username, password)

Delete user

db.removeUser(username)

4. The index ensureIndex ()


// Normal index
db.persons.ensureIndex({name:1});
 
db.factories.insert({name: "xyz", metro: {city: "New York", state: "NY"}});
// Document index
db.factories.ensureIndex({metro : 1});
 
// Embedded index
db.factories.ensureIndex({"metro.city": 1});
 
// Composite index
db.things.ensureIndex({name: -1, qty: 1});
 
// only 1 The index
db.user.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
 
/* when 1 A record is inserted into only 1 When indexing a document, the missing fields will be null The document is inserted for the default values */
db.things.save({lastname: "Smith"});
// The following operation will fail because firstname There are only 1 Sex index, the value is null
db.things.save({lastname: "Jones"});
 
// View index
db.persons.getIndexes();
 
// Delete all indexes
db.collection.dropIndexes();
 
// Drop a single index
db.collection.dropIndex({x: 1, y: -1});

5. Add, delete, change, check, etc


// Definition document
>doc = {
    "_id"      : 1,
    "author"   : "sam",
    "title"    : "i love you",
    "text"     : "this is a test",
    "tags"     : [ "love", "test" ],
    "comments" : [
                   { "author" : "jim", "comment" : "yes" },
                   { "author" : "tom", "comment" : "no" }
                 ]
}
 
// Inserted into the document
> db.posts.insert(doc);
 
// Find the document
> db.posts.find({'comments.author':'jim'});

Query Query

// All records in the query collection: 
db.users.find({})
 
// Query out all " last_name " Attribute values for " Smith " Document record
db.users.find({'last_name': 'Smith'})

 
Query options

D:/mongodb/bin>mongo.exe
MongoDB shell version: 2.4.8
connecting to: test
>
4
 
Conditional expression
 
1) < , < =, > , > =

D:/mongodb/bin>mongo.exe
MongoDB shell version: 2.4.8
connecting to: test
>
5
The $all operation is similar to the $in operation, but the $all operation requires that all the values in the array be included in the returned record

D:/mongodb/bin>mongo.exe
MongoDB shell version: 2.4.8
connecting to: test
>
6
The $exists operation checks to see if a field exists

D:/mongodb/bin>mongo.exe
MongoDB shell version: 2.4.8
connecting to: test
>
7
 
The $mod operation allows us to simply take a module

D:/mongodb/bin>mongo.exe
MongoDB shell version: 2.4.8
connecting to: test
>
8
$ne means not equal to (not equal)

D:/mongodb/bin>mongo.exe
MongoDB shell version: 2.4.8
connecting to: test
>
9
The $in operation is similar to IN in a traditional relational database
// The database has records for all arrays  
> db.user.find( { _id : { $in : [ 2, 3 ] } } ).limit(5);
{ "_id" : 2, "name" : "user2", "userid" : 2, "age" : 20 }
{ "_id" : 3, "name" : "user3", "userid" : 3, "age" : 20 }

$nin is the opposite of the $in operation

// deducted _id = 1/2/3/4 The record of
> db.user.find( { _id : { $nin : [ 1, 2, 3, 4 ] } } ).limit(5);
{ "_id" : 0, "name" : "user0", "userid" : 0, "age" : 20 }
{ "_id" : 5, "name" : "user5", "userid" : 5, "age" : 20 }
{ "_id" : 6, "name" : "user6", "userid" : 6, "age" : 20 }

$or
> db.user.find( { $or : [ { _id : 2 }, { name : 'user3' }, { userid : 4 } ] } ).limit(5); 
{ "_id" : 2, "name" : "user2", "userid" : 2, "age" : 20 }
{ "_id" : 3, "name" : "user3", "userid" : 3, "age" : 20 }
{ "_id" : 4, "name" : "user4", "userid" : 4, "age" : 20 }
>

$nor is the opposite of $or
> db.user.find( { $nor : [ { _id : 2 }, { name : 'user3' }, { userid : 4 } ] } ).limit(4); 
{ "_id" : 0, "name" : "user0", "userid" : 0, "age" : 20 }
{ "_id" : 1, "name" : "user1", "userid" : 1, "age" : 20 }
{ "_id" : 5, "name" : "user5", "userid" : 5, "age" : 20 }
{ "_id" : 6, "name" : "user6", "userid" : 6, "age" : 20 }
>

The $size operation will query the array length equal to the array of input parameters
> db.things.find(); 
{ "_id" : ObjectId("4de73360059e7f4bdf907cfe"), "a" : [ 1, 2, 3 ] }
 
> db.things.find( { a : { $size : 3 } } );
{ "_id" : ObjectId("4de73360059e7f4bdf907cfe"), "a" : [ 1, 2, 3 ] }
 
> db.things.find( { a : { $size : 2 } } );
>
> db.things.find( { a : { $size : 1 } } );
>

$where
> db.mycollection.find( { $where : function() { return this.a == 3 || this.b == 4; } } ); 
// Ditto effect
> db.mycollection.find( function() { return this.a == 3 || this.b == 4; } );

$type will retrieve the data based on the BSON type of the field

// return a Is a record of a string
> db.things.find( { a : { $type : 2 } } );
 
// return a is int Type record
> db.things.find( { a : { $type : 16 } } );

Type name mapping

Low Double: 1
Low String: 2
Low Object: 3
Low Array: 4
● Binary data: 5
● Object id: 7
Low Boolean: 8
Low Date: 9
Low Null: 10
● Regular expression: 11
● JavaScript code: 13
Low Symbol: 14
● JavaScript code with scope: 15
● 32-bit integer: 16
Low Timestamp: 17
● 64-bit integer: 18
● Min key: 255
● Max key: 127


Mongodb also supports regular expression retrieval


// retrieve name Attribute is u At the beginning, 4 End of all users
> db.user.find( { name : /u.*4$/i } ).limit(2);
{ "_id" : 4, "name" : "user4", "userid" : 4, "age" : 20 }
{ "_id" : 14, "name" : "user14", "userid" : 14, "age" : 20 }
 
// A query statement with the same effect
> db.user.find( { name : { $regex : 'u.*4$', $options : 'i' } } ).limit(2);
{ "_id" : 4, "name" : "user4", "userid" : 4, "age" : 20 }
{ "_id" : 14, "name" : "user14", "userid" : 14, "age" : 20 }
 
// Cooperate with other operations 1 The use
> db.user.find( { name : { $regex : 'u.*4$', $options : 'i', $nin : [ 'user4' ] } } ).limit(2);
{ "_id" : 14, "name" : "user14", "userid" : 14, "age" : 20 }
 

The sorting
 
An ascending sort by the last_name property returns all documents


//1 Is the ascending order, -1 According to descending order
db.users.find( {} ).sort( { last_name : 1 } );

Group
// Grammar: 
db.coll.group( {
       cond     : {filed : conditions},
       key      : {filed: true},
       initial  : {count: 0, total_time:0},
       reduce   : function(doc, out){ },
       finalize : function(out){}
} );
 
Parameter description:
   Key         : proceed to that field
   Group Cond  : query conditions
   Initial     Initialization: group counter
   Reduce      : usually do statistical operation
   Finalize    : statistics are usually carried out 1 Step operations, such as averaging Keyf : 1 Three functions to return 1 An alternative KEY The value of the
   
// example
> db.test.group( {
       cond     : { "invoked_at.d" : { $gte : "2009-11", $lt : "2009-12" } },
       key      : {http_action: true},
       initial  : {count: 0, total_time:0},
       reduce   : function( doc, out ){ out.count++; out.total_time += doc.response_time },
       finalize : function(out){ out.avg_time = out.total_time / out.count } } );
   
[
  {
    "http_action" : "GET /display/DOCS/Aggregation",
    "count"       : 1,
    "total_time"  : 0.05,
    "avg_time"    : 0.05
  }
]
 


Deduplication is similar to Distinct in a relational database

> db.addresses.insert( { "zip-code" : 10010 } ) 
> db.addresses.insert( { "zip-code" : 10010 } )
> db.addresses.insert( { "zip-code" : 99701 } )
>
> db.addresses.distinct("zip-code");
[ 10010, 99701 ]
>
> //command model :
> db.runCommand( { distinct: 'addresses', key: 'zip-code' } )
{ "values" : [ 10010, 99701 ] }
>
> db.comments.save( { "user" : { "points" : 25 } } )
> db.comments.save( { "user" : { "points" : 31 } } )
> db.comments.save( { "user" : { "points" : 25 } } )
> db.comments.distinct("user.points");
[ 25, 31 ]

Mongodb supports the skip and limit commands for paging queries

use persons
1
$elemMatch
use persons
2
The count() method returns the total number of query records
use persons
3
$slice
use persons
4
Delete Delete
 
The Remove operation is used to delete records from the collection
use persons
5
Update Update
use persons
6
Parameter description:
      Criteria: object used to set query conditions
      Objnew    : object used to set the update content
      Upsert    : if the record already exists, update it, otherwise add a new record
      Multi      : if there are multiple eligible records, update them all note: by default, only the first eligible record is updated
 
save()
use persons
7
$inc

{ $inc : { field : value } } // the field The value of the add 1 a value
 
> db.user.findOne( { _id : 0 } );
{ "_id" : 0, "name" : "user0", "userid" : 0, "age" : 22 }
> db.user.update( { _id : 0 }, { $inc : { age : 1 } } );
{ "_id" : 0, "name" : "user0", "userid" : 0, "age" : 23 }

$set

{ $set : { field : value } } 
// the field Is set to value when field When it doesn't exist, it increases 1 A field,
// similar SQL the set Operation, value Support all types
 
// Put the above age Change back to 20
> db.user.update( { _id : 0 }, { $set : { age : 20 } } );
{ "_id" : 0, "name" : "user0", "userid" : 0, "age" : 20 }
 
// when field When it doesn't exist, it increases 1 A field
> db.user.update( { _id : 0 }, { $set : { sex : 'boy' } } );
{ "_id" : 0, "sex" : "boy", "name" : "user0", "userid" : 0, "age" : 20 }

$unset

{ $unset : { field : 1} } // Deletes the given field field
 
// Delete the 1 Step increase of sex field
> db.user.update( { _id : 0 }, { $unset : { sex : 1 } } );
{ "_id" : 0, "name" : "user0", "userid" : 0, "age" : 20 }

$push

{ $push : { field : value } }
// if filed is 1 Two existing arrays, so let's say value Additional to field
// if field It didn't exist before, so add it field The fields, value The value is assigned to field
// if field Yes, but no 1 I'm going to make an error
 
> db.sport.update( { _id : 0 }, { $push : { aihao : 'football' } } );

$pushAll
db  ||  db.getName()
2
$addToSet

{ $addToSet : { field : value } }
// if filed is 1 Two existing arrays, and value It's not one of them value Add to array
// if filed It doesn't exist, so let's say value As a 1 I'm going to assign it in array form field
// if field is 1 Two existing non-array types, and an error will be reported

$pop

{ $pop : { field : 1 } }   // Delete the end of the array 1 An element
 
{ $pop : { field : -1 } }  // Deletes the first in the array 1 An element

$pull

{ $pull : { field : _value } }
// if field is 1 Array, then delete matches _value Retrieve a record of conditions
// if field is 1 Two nonarrays that already exist, then an error will be reported

$pullAll

{ $pullAll : { field : value_array } } // with $push Similar, just value The data type is 1 An array

$rename

{ $rename : { old_field_name : new_field_name } 
// Rename the specified field name from 1.7.2 Support started after version
 
> db.user.update( { _id : 0 } , { $rename : { 'quantity' : 'qty'}});

Special operator: $

The $operator represents the first entry in the query record that matches the condition
 


// case 1
> db.t.find()
{
  "_id"      : ObjectId("4b97e62bf1d8c7152c9ccb74"),
  "title"    : "ABC",
  "comments" : [
                 { "by" : "joe", "votes" : 3 },
                 { "by" : "jane", "votes" : 7 }
               ]
}
> db.t.update( { 'comments.by' : 'joe' }, { $inc : { 'comments.$.votes' : 1 } }, false, true )
> db.t.find()
{
  "_id"      : ObjectId("4b97e62bf1d8c7152c9ccb74"),
  "title"    : "ABC",
  "comments" : [
                 { "by" : "joe", "votes" : 4 },
                 { "by" : "jane", "votes" : 7 }
               ]
}
 
// case 2
> db.t.find();
{
  "_id" : ObjectId("4b9e4a1fc583fa1c76198319"),
  "x"   : [ 1, 2, 3, 2 ]
}
> db.t.update( { x : 2 }, { $inc : { "x.$": 1 } }, false, true);
> db.t.find();
{
  "_id" : ObjectId("4b9e4a1fc583fa1c76198319"),
  "x"   : [ 1, 3, 3, 2 ]
}
 
// In an array $ Cooperate with $unset operation Instead of deleting the matched element, the effect is to change the matched element to null , such as:
> db.t.insert( { x: [ 1, 2, 3, 4, 3, 2, 3, 4 ] } )
> db.t.find()
{
  "_id" : ObjectId("4bde2ad3755d00000000710e"),
  "x"   : [ 1, 2, 3, 4, 3, 2, 3, 4 ]
}
> db.t.update( { x : 3 }, { $unset : { "x.$" : 1 } } )
> t.find()
{
  "_id" : ObjectId("4bde2ad3755d00000000710e"),
  "x"   : [ 1, 2, null, 4, 3, 2, 3, 4 ]
}

 
Graphical management tool
 
MongoDB has several graphical management tools for reference:
http://docs.mongodb.org/ecosystem/tools/administration-interfaces/
 


Related articles: