Introduction to mongodb (including installation, common commands, related concepts, tips, common operations, etc.)

Time:2020-5-1

1、 Installation and configuration
 
Mongodb’s official download site is http://www.mongodb.org/downloads, where you can download the latest installation program
 
Windows platform installation
 
● step 1: Download mongodb
Click the official download address above and download the Windows version

● step 2: set mongodb program storage directory
After downloading, unzip to the custom folder, for example: D: \ mongodb\

● step 3: set the data file storage directory
Create the DB and logs folders (the same level as the bin directory) in the D: \ mongodb \,
Then create the mongodb.log log file in the logs folder

● step 4: start mongodb service as windows service

Copy codeThe code is as follows:
//Enter the CMD console
D:/mongodb/bin>mongod.exe –logpath D:/mongodb/logs/mongodb.log –logappend
                          –dbpath D:/mongodb/db
                          –directoryperdb
                          –serviceName MongoDB
                          –install
–Directoryperdb specifies that each DB will create a new directory

After installation, you can start and stop mongodb with the commands net start mongodb and net stop mongodb under CMD
 
● step 5: client connection verification
Open CMD and input: D: / mongodb / bin > mongo.exe

Copy codeThe code is as follows:
D:/mongodb/bin>mongo.exe
MongoDB shell version: 2.4.8
connecting to: test
>

 
Linux platform installation
 
● step 1: Download mongodb
Click the official download address above and download the Linux version

● step 2: set mongodb program storage directory
After downloading, unzip to the custom folder, for example, / usr / local / Mongo

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

● step 4: start mongodb service randomly as Linux service

Copy codeThe code is as follows:
VI / etc / RC. Local / / open the configuration file using the VI editor and add the following line to it
 
/usr/local/mongo/bin/mongod –dbpath=/data/db/ –logpath=/data/logs/mongodb.log –logappend& 

After the installation is complete, you can use pkill mongod to finish
 
2、 Data logical structure
 
● mongodb document, equivalent to a row of records in the relational database.
● multiple documents form a collection, which is equivalent to a table in a relational database.
● multiple collections, logically organized together, are databases.
● a mongodb instance supports multiple databases.
● default port: 27017
 
3、 Common commands
 
Select database

Copy codeThe code is as follows:
use persons

Show current database

Copy codeThe code is as follows:
db  ||  db.getName()

Delete current database

Copy codeThe code is as follows:
db.dropDatabase()

Display collection under current database

Copy codeThe code is as follows:
show tables || show collections

Display the current system.profile

Copy codeThe code is as follows:
show profile

Display users under the current database

Copy codeThe code is as follows:
show users

Add user

Copy codeThe code is as follows:
db.addUser(username, password)

delete user

Copy codeThe code is as follows:
db.removeUser(username)

4、 Index ensureindex()

Copy codeThe code is as follows:
//General 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});
 
//Unique index
db.user.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
 
/*When a record is inserted into a unique index document, the missing field will be inserted into the document with null as the default value*/
db.things.save({lastname: “Smith”});
//The following operation will fail because there is a unique index on firstname and the value is null
db.things.save({lastname: “Jones”});
 
//View index
db.persons.getIndexes();
 
//Delete all indexes
db.collection.dropIndexes();
 
//Delete a single index
db.collection.dropIndex({x: 1, y: -1});

5、 Add, delete, change, check, etc

Copy codeThe code is as follows:
//Define 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” }
                 ]
}
 
//Insert document
> db.posts.insert(doc);
 
//Find document
> db.posts.find({‘comments.author’:’jim’});

Query query

Copy codeThe code is as follows:
//Query all records in the collection:
db.users.find({})
 
//Query out all document records with the value of “Smith” in the “last_name” attribute
db.users.find({‘last_name’: ‘Smith’})

 
query option

Copy codeThe code is as follows:
//Returns all fields except the age field
> db.user.find( {},{ age : 0 } );
 
//Return tags = tennis all columns except comments
> db.posts.find( { tags : ‘tennis’ }, { comments : 0 } );
 
//Return the name field with userid = 16
> db.user.find( { userid : 16 },{ name : 1 } );
//Return result:
{ “_id” : 16, “name” : “user16” }
 
//Return all Z fields of x = John
> db.things.find( { x : “john” }, { z : 1 } );
 
//Note: the “Id” field will always be returned, even if it is not explicitly specified

 
Conditional expression
 
1) <, <=, >, >=

Copy codeThe code is as follows:
//Greater than: field > value
> db.collection.find( { “field” : { $gt : value } } );
 
//Less than: field < value
> db.collection.find( { “field” : { $lt : value } } );
 
//Greater than or equal to: field > = value
> db.collection.find( { “field” : { $gte : value } } );
 
//Less than or equal to: field < = value
> db.collection.find( { “field” : { $lte : value } } );
 
//Interval query 5 < field < = 10
> db.collection.find( { “field” : { $gt : 5, $lte : 10 } } );

$all operation is similar to $in operation, but the difference is that the $all operation requires that all the values in the array be included in the returned record

Copy codeThe code is as follows:
> use test;
switched to db test
> db.things.insert( { a : [ 1, 2, 3 ] } );
 
> db.things.find();
{ “_id” : ObjectId(“4de73360059e7f4bdf907cfe”), “a” : [ 1, 2, 3 ] }
 
> db.things.find( { a : { $all : [ 2, 3 ] } } );
{ “_id” : ObjectId(“4de73360059e7f4bdf907cfe”), “a” : [ 1, 2, 3 ] }
 
> db.things.find( { a : { $all : [ 1, 2, 3 ] } } );
{ “_id” : ObjectId(“4de73360059e7f4bdf907cfe”), “a” : [ 1, 2, 3 ] }
 
> db.things.find( { a : { $all : [ 1 ] } } );
{ “_id” : ObjectId(“4de73360059e7f4bdf907cfe”), “a” : [ 1, 2, 3 ] }
 
> db.things.find( { a : { $all : [ 1, 2, 3, 4 ] } } );
>
>

$existsOperation to check whether a field exists

Copy codeThe code is as follows:
//Userid field exists
> db.user.find( { userid : { $exists : true } } ).limit(1);
{ “_id” : 1, “name” : “user1”, “userid” : 1, “age” : 20 }
//Sex field does not exist
> db.user.find( { sex : { $exists : true } } ).limit(1);
>
>

 
$modOperation allows us to simply carry out mold taking operation

Copy codeThe code is as follows:
//Where clause
> db.user.find( “this._id%10==1” ).limit(5);
 
//$mod operation
> db.user.find( { _id : { $mod : [ 10, 1 ] } } ).limit(5);

$neIt means not equal

Copy codeThe code is as follows:
> db.user.find().limit(2);
{ “_id” : 0, “name” : “user0”, “userid” : 0, “age” : 20 }
{ “_id” : 1, “name” : “user1”, “userid” : 1, “age” : 20 }
 
> db.user.find( { _id : { $ne : 0 } } ).limit(2);
{ “_id” : 1, “name” : “user1”, “userid” : 1, “age” : 20 }

$inOperation is similar to in in in traditional relational database

Copy codeThe code is as follows:
//There are records corresponding to all arrays in the database
> 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 }

$ninOpposite to $in operation

Copy codeThe code is as follows:
//Deduct records with ﹐ id = 1 / 2 / 3 / 4
> 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

Copy codeThe code is as follows:
> 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 }
>

$norOpposite to $or

Copy codeThe code is as follows:
> 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 }
>

$sizeThe operation will query an array whose length is equal to the input parameter

Copy codeThe code is as follows:
> 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

Copy codeThe code is as follows:
> 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; } );

$typeData will be retrieved based on the bson type of the field

Copy codeThe code is as follows:
//Returns a as a string record
> db.things.find( { a : { $type : 2 } } );
 
//Returns a record of type int
> db.things.find( { a : { $type : 16 } } );

Type name mapping

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

Mongodb also supports regular expression retrieval

Copy codeThe code is as follows:
//Retrieve all users whose name attribute starts with u and ends with 4
> 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 }
 
//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 }
 
//Use with other operations
> db.user.find( { name : { $regex : ‘u.*4$’, $options : ‘i’, $nin : [ ‘user4’ ] } } ).limit(2);
{ “_id” : 14, “name” : “user14”, “userid” : 14, “age” : 20 }
 

sort
 
Sort all documents in ascending order according to last name attribute

Copy codeThe code is as follows:
//1 for ascending order, – 1 for descending order
db.users.find( {} ).sort( { last_name : 1 } );

Group

Copy codeThe code is as follows:
//Syntax:
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: for that field
Group cond: query criteria
Initial: initialize group counter
Reduce: usually do statistical operations
Finalize: usually the statistics result is used for further operations, such as average keyf: a function is used to return the value of an alternative key
   
//Examples
> 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
  }
]
 

Duplicate removalSimilar to distinct in relational database

Copy codeThe code is as follows:
> 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 mode:
> 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 skip and limit commands for paging queries

Copy codeThe code is as follows:
//Skip top 10 records
> db.user.find().skip(10);
//8 records per page
> db.user.find().limit(8);
//Skip the first 20 records and return 10 records per page
> db.user.find().skip(20).limit(8);
//The following statement is the same as the last one, but it is not clear enough
> db.user.find({}, {}, 8, 20);

$elemMatch

Copy codeThe code is as follows:
> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
{ “_id” : ObjectId(“4b5783300334000000000aa9”), “x” : [ { “a” : 1, “b” : 3 }, 7, { “b” : 99 }, { “a” : 11 } ] }
 
//Same effect
> t.find( { “x.a” : 1, “x.b” : { $gt : 1 } } )

The count() method returns the total number of query records

Copy codeThe code is as follows:
db.orders.count( { ord_dt : { $gt : new Date(’01/01/2012′) } } )
//Same effect
db.orders.find( { ord_dt : { $gt : new Date(’01/01/2012′) } } ).count()
 
//When the skip () and limit () methods are used in the query statement,
//By default, count () ignores these methods. If you want to calculate these methods,
//You need to pass a true parameter to the count() method
> db.user.find( { _id : { $lt : 20 } } ).skip(3).limit(9).count();
20
> db.user.find( { _id : { $lt : 20 } } ).skip(3).limit(9).count(true);
9
>

$slice

Copy codeThe code is as follows:
DB. Posts. Find ({}, {comments: {$slice: 5}) / / top 5 comments
DB. Posts. Find ({}, {comments: {$slice: – 5}) / / last 5 comments
DB. Posts. Find ({}, {comments: {$slice: [20, 10]}) / / skip 20, limit 10
DB. Posts. Find ({}, {comments: {$slice: [- 20, 10]}}) / / last 20, limit 10
 

Delete
 
The remove operation is used to remove records from the collection

Copy codeThe code is as follows:
//Delete a record
> db.stu.remove( { _id : 17 } );
 
//Delete all records
> db.stu.remove( {} );
 
//In some cases, when you are performing a remove operation on a record,
//There may be an update operation on the record, so that the record may not be deleted,
//If you find this unsatisfactory, you can add $atomic to the remove operation:
db.stu.remove( { rating : { $lt : 3.0 }, $atomic : true } );

Update

Copy codeThe code is as follows:
db.collection.update( criteria, objNew, upsert, multi )

Parameter Description:
Criteria: object used to set query criteria
Objnew: object used to set update content
Upsert: if the record already exists, update it; otherwise, add a new record
Multi: if there are multiple eligible records, update all note: by default, only the first eligible record will be updated
 
save()

Copy codeThe code is as follows:
//If there is an update, if not, a new record will be added
db.mycollection.save( { name : ‘shawn’ } );

$inc

Copy codeThe code is as follows:
{$Inc: {field: value}} / / add a value to the value of the field
 
> 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

Copy codeThe code is as follows:
{ $set : { field : value } } 
//Set the value of the field to value. When the field does not exist, add a field,
//Similar to SQL set operation, value supports all types
 
//Change the age back to 20
> db.user.update( { _id : 0 }, { $set : { age : 20 } } );
{ “_id” : 0, “name” : “user0”, “userid” : 0, “age” : 20 }
 
//Add a field when the field does not exist
> db.user.update( { _id : 0 }, { $set : { sex : ‘boy’ } } );
{ “_id” : 0, “sex” : “boy”, “name” : “user0”, “userid” : 0, “age” : 20 }

$unset

Copy codeThe code is as follows:
{$unset: {field: 1}} / / delete the given field
 
//Delete the sex field added in the previous step
> db.user.update( { _id : 0 }, { $unset : { sex : 1 } } );
{ “_id” : 0, “name” : “user0”, “userid” : 0, “age” : 20 }

$push

Copy codeThe code is as follows:
{ $push : { field : value } }
//If filed is an existing array, append value to field
//If the field does not exist, add a new field and assign the value to the field
//If the field exists but is not an array, an error will occur
 
> db.sport.update( { _id : 0 }, { $push : { aihao : ‘football’ } } );

$pushAll

Copy codeThe code is as follows:
{ $pushAll : { field : value_array } }
//The function is the same as $push, except that the value here is an array, which is equivalent to $push for each value in the array

$addToSet

Copy codeThe code is as follows:
{ $addToSet : { field : value } }
//If filed is an existing array and value is not in it, add value to the array
//If the file does not exist, assign value to the field as an array
//If the field is an existing non array type, an error will be reported

$pop

Copy codeThe code is as follows:
{$Pop: {field: 1}} / / delete the last element in the array
 
{$Pop: {field: – 1}} / / delete the first element in the array

$pull

Copy codeThe code is as follows:
{ $pull : { field : _value } }
//If the field is an array, delete the records that meet the search criteria of “value”
//If the field is an existing non array, an error will be reported

$pullAll

Copy codeThe code is as follows:
{$pullall: {field: value [array}} / / similar to $push, except that the data type of value is an array

$rename

Copy codeThe code is as follows:
{ $rename : { old_field_name : new_field_name } 
//Rename the specified field name, supported since version 1.7.2
 
> db.user.update( { _id : 0 } , { $rename : { ‘quantity’ : ‘qty’}});

Special operators:$

The $operator represents the entry of the first matching condition in the query record
 

Copy codeThe code is as follows:
/ / 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 ]
}
 
//When $is used with the $unset operator in the array, the effect is not to delete the matched element, but 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 tools
 
Mongodb has several graphical management tools, for reference:
http://docs.mongodb.org/ecosystem/tools/administration-interfaces/
 

Recommended Today

A detailed explanation of the differences between Perl and strawberry Perl and ActivePerl

Perl is the abbreviation of practical extraction and report language “practical report extraction language”. Application of activestateperl and strawberry PERL on Windows platformcompiler。 Perl   The relationship between the latter two is that C language and Linux system have their own GCC. The biggest difference between activestate Perl and strawberry Perl is that strawberry Perl […]