First, install the MONGODB Linux environment installation
Take the Ubuntu 14.04 I use as an example
1. Installing MongoDB
Apt-get Install MongoDB
2. Creating a database directory for MongoDB
Mkdir-p/data/db
3. View MongoDB Run status
Mongod
Found an error error:insufficient free space for journal files
As set here, we can access Mongod.
4. Visit Mongod
Mongo
Windows Environment Installation
After the installation of the official download installation package, we need to set up the DB directory in C drive
C:\data\db
Then run Mongod in the installation directory
Ii. MongoDB Tools
1. Mongo
MongoDB client, is a JavaScript Shell
2. Mongoimport
Data Import Tool, JSON,CSV,TSV
3. Mongoexport
Data Export Tool Json,csv
4. Mongodump
Binary Export (Backup)
5. Mongorestore
Restores a binary export
5. Bsondump
Convert exported binaries to JSON
6.mongostat
Displays the current status of the MongoDB server at a glance
7. BSON
JSON binary form that supports data types that are not JSON
http://bsonspec.org
8. Mongo DB Drive
https://docs.mongodb.org/ecosystem/drivers/
Iii. Creating databases and documents
1. Create a database
In MongoDB, with the use command, if there is no database, MongoDB will automatically ' create '
2. Displaying data that is currently present
Db.links.count ()
3. Inserting a document
Just give the JSON-formatted document (where links is the table name)
Db.links.insert ({title: "BI HELL", url: "http://bihell.com", Comment: "Great blog", tags:["tutorials", "Dev"], saved_on: New Date ()});
4. Create another document
> var doc = {};
> doc.title = "BI HELL";
BI HELL
> doc.url = ' http://bihell.com '
Http://bihell.com
> doc.tags = ["BI", "SSIS"];
["BI", "SSIS"]
> doc.saved_on = new Date
Isodate ("2015-09-15t14:45:00.112z")
> Doc.meta ={}
{ }
> doc.meta.browser = "Internet expolorer 11"
Internet Expolorer 11
> Doc.meta.OS = "Windows 10"
Windows 10
> Doc
{
"title": "BI HELL",
"url": "Http://bihell.com",
"Tags": [
"BI",
"SSIS"
],
"Saved_on": Isodate ("2015-09-15t14:45:00.112z"),
"Meta": {
"Browser": "Internet expolorer 11",
"OS": "Windows 10"
}
}
> Db.links.save (DOC)
>
5. Querying data
> Db.links.find ()
{"_id": ObjectId ("55f82dbfbe4d5bc5bdb1c366"), "title": "BI HELL", "url": "http://bihell.com", "comment": "Great Blog" , "tags": ["Tutorials", "Dev"], "saved_on": Isodate ("2015-09-15t14:39:59.445z")}
{"_id": ObjectId ("55f83002be4d5bc5bdb1c367"), "title": "Bi HELL", "url": "Http://bihell.com", "tags": ["Bi," "SSIS "]," saved_on ": Isodate (" 2015-09-15t14:45:00.112z ")," meta ": {" browser ":" Internet expolorer One "," OS ":" Windows 10 " } }
>
Some more practice.
> Db.users.insert ({name: "Andrew"})
> var a =db.users.findone ({name: "Andrew"});
> A
{"_id": ObjectId ("55f97afaf6986758f851295e"), "name": "Andrew"}
> a._id
ObjectId ("55f97afaf6986758f851295e")
> Db.links.insert ({title: "Bihell", url: "http://bihell.com", userid:a._id})
> Db.links.find ()
{"_id": ObjectId ("55f97c23f6986758f8512960"), "title": "Bihell", "url": "Http://bihell.com", "UserId": ObjectId ("55f9 783bf6986758f851295d ")}
> link = db.links.find () [0]
> Db.users.findOne ({_id:link.userid});
{"_id": ObjectId ("55f9783bf6986758f851295d"), "name": "Andrew"}
>
Iv.. ID
The ObjectId ("_id": ObjectId ("55f82dbfbe4d5bc5bdb1c366") in the previous query was generated by MongoDB by default. We can specify it at the time of insertion
> Db.links.insert ({_id:3, Name: "Test"});
Returns the first record of a query result
> db.links.find () [0]
Returns the ID of the first record
> Db.links.find () [0]._id
Get record creation time (System-generated objectid only works)
Db.links.find () [3]._id.gettimestamp ()
Of course, you can generate a objectid yourself.
> New ObjectId
ObjectId ("55f838989bf562500ae2a5fa")
Five, inquiry
have been exposed to some queries before, now for a bit complex.
Download Bookmarks.js
https://searchcode.com/codesearch/view/93349316/
Connect the machine and execute bookmarks.js
MONGO 127.0.0.1/bookmarks Bookmarks.js
Connecting the Bookmarks Database
MONGO bookmarks
We look at the links table. There's some data.
> Db.links.find ()
The above is just a list of all rows of records, if the lot better point, directly displayed as a JSON style, you can write this
> Db.users.find (). ForEach (Printjson)
Query like Select to find the record of email as '[email protected]'
Db.users.find ({email: '[email protected]');
Db.users.find ({passwordhash: ' Another_password_hash '}). ForEach (Printjson);
Use FindOne to return only one record
> Db.links.findOne ({favorites:100});
Use FindOne to display only email= '[email protected]' name
> db.users.findOne ({email: '[email protected]'). Name
Set the fields that need to be displayed, in the example title and URL, where 1 and ture are equivalent
> Db.links.find ({favorites:100},{title:1, url:true});
Do not show tags fields
> Db.links.find ({favorites:100},{tags:0}). ForEach (Printjson);
Querying child objects
> Db.users.findOne ({' Name.first ': ' John '});
{
"_id": ObjectId ("55f983616ffe01d4461ef223"),
' Name ': {
"First": "John",
"Last": "Doe"
},
"Age": 30,
"Email": "[email protected]",
"PasswordHash": "Some_password_hash",
"Logins": [
{
"At": Isodate ("2012-04-03t21:06:07z"),
"Minutes": 20
},
{
"At": Isodate ("2012-04-15t08:17:18z"),
"Minutes": 18
},
{
"At": Isodate ("2012-04-30t18:03:04z"),
"Minutes": 34
}
]
}
Show only last in name sub-object
> Db.users.findOne ({' Name.first ': ' John '},{' name.last ': 1});
{
"_id": ObjectId ("55f983616ffe01d4461ef223"),
' Name ': {
"Last": "Doe"
}
}
Operator
Find records with favorites greater than 50 and return only the title and favorites columns
> Db.links.find ({favorites: {$gt: 50}},{title:1, favorites:1,_id:0});
Less than $LT
> Db.links.find ({favorites: {$lt: 150}},{title:1, favorites:1,_id:0});
Less than or equal to $lte
> Db.links.find ({favorites: {$lte: 150}},{title:1, favorites:1,_id:0});
Greater than or equal to $gte
> Db.links.find ({favorites: {$gte: 150}},{title:1, favorites:1,_id:0});
Greater than 100 less than 300
> Db.links.find ({favorites: {$gt: +, $lt: 300}},{title:1, favorites:1,_id:0});
Not equal to
> Db.links.find ({tags: {$ne: ' Code '}},{title:1,tags:1});
Inch
> Db.users.find ({' Name.first ': {$in: [' John ', ' Jane ']}},{' Name.first ': 1});
> Db.links.find ({tags: {$in: [' Marketplace ', ' Code ']}},{title:1,tags:1,_id:0})
Not in
> Db.users.find ({' Name.first ': {$nin: [' John ', ' Jane ']}},{' Name.first ': 1});
$all Match All results
> Db.links.find ({tags: {$all: [' Marketplace ', ' Code ']}},{title:1,tags:1,_id:0})
Or
> Db.users.find ({$or: [{' Name.first ': "John"},{' name.last ': "Wilson"}]},{name:1});
Not or find ' name.first ' not for John or ' Name.last ' is not a record for Wilson
> Db.users.find ({$nor: [{' Name.first ': "John"},{' name.last ': "Wilson"}]},{name:1});
and
> Db.users.insert ({name:{first: "John", Last: "Jones"});
> Db.users.find ({$and: [{' Name.first ': ' John '},{' name.last ': ' Jones '}]});
Exist
> Db.users.find ({email:{$exists: true}},{name:1,_id:0});
Not exist
> Db.users.find ({email:{$exists: false}},{name:1,_id:0});
Take the remainder mod to find favorites with a record of more than 5 0
> Db.links.find ({favorites:{$mod: [5,0]}},{title:1,favorites:1,_id:0})
Find Favorites In addition to 5 not more than 0 records
> Db.links.find ({favorites:{$not: {$mod: [5,0]}}},{title:1,favorites:1,_id:0})
Find the minutes=20 record in the Logins field
> Db.users.find ({logins: {$elemMatch: {minutes:20}}});
Find records for at <2012-03-30 in the Logins field (note that the date differs from the MongoDB date)
> Db.users.find ({logins: {$elemMatch: {at: {$lt: New Date (2012,03,14)}}}). ForEach (Printjson);
Use $where (ie, use JS, as little as possible, inefficient)
Db.users.find ({$where: ' this.name.first=== ' John '})
Db.users.find ({$where: ' this.name.first=== ' John ', age:30})
If you just use where, you can omit $where
Db.users.find (' this.name.first=== ' John ')
Using functions
> var f = function () {return This.name.first = = = "John"};
> Db.users.find (f);
> Db.users.find ({$where: F});
Go heavy
> db.links.distinct (' Favorites ');
grouping aggregations
For a specific explanation of the group, you can see here.
> Db.links.group ({
... key: {userid:true},
... initial: {favcount:0},
... reduce:function (doc,o) {o.favcount + = doc.favorites},
... finalize:function (o) {o.name = Db.users.findOne ({_id:o.userid}). Name;}} );
Regular
> Db.links.find ({title:/tuts\+$/});
> Db.links.find ({title:/tuts\+$/},{title:1});
> Db.links.find ({title: {$regex:/tuts\+$/}},{title:1});
> Db.links.find ({title: {$regex:/tuts\+$/, $ne: "mobiletuts+"}},{title:1});
Count
Db.users.find ({' Name.first ': ' John '}). Count ();
Db.users.count ({' Name.first ': ' John '});
Db.users.count ();
Sort
Sort inside 1 is positive sequence-1 for reverse order
Db.links.find ({},{title:1, _id:0}). Sort ({title:1});
> Db.links.find ({},{title:1,favorites:1, _id:0}). Sort ({favorites: -1,title:1});
Limit the number of returned records
> Db.links.find ({},{title:1, favourites:1,_id:0}). Sort ({favorites:-1}). Limit (1);
> Db.links.find (). Limit (2). ForEach (Printjson);
Page out
> Db.links.find ({},{title:1, _id:0}). Skip (0*3). Limit (3);
> Db.links.find ({},{title:1, _id:0}). Skip (1*3). Limit (3);
> Db.links.find ({},{title:1, _id:0}). Skip (2*3). Limit (3);
Vi.. Update
Update
Locate the Name.first=john record, and then update the job value to developer
> db.users.update ({' Name.first ': ' John '},{job: ' Developer '});
Note: Only the first record that is matched is updated, and the fourth parameter is set to Ture to update all records
> db.users.update ({' Name.first ': ' Jane '},{$set: {job: "developer"}},false,true);
When the third parameter is set to Ture, if the matching record of the first parameter is not found, the parameter 2 is inserted directly as a new record
> db.users.update ({name: "Kate Wills"},{name: "Kate Wills", Job: "LISP Developer"},true);
> Db.users.find ({name: "Kate Wills"});
Update a value
> var n = {title: "nettuts+"};
> Db.links.find (n, {title:1, favorites:1});
> db.links.update (n,{$inc: {favorites:5}}); --The original value plus 5
> Db.links.find (n, {title:1, favorites:1});
SET
If the original field is updated, no insert a field directly
> var q = {name: "Kate Wills"};
> Db.users.find (q);
{"_id": ObjectId ("5602bcd248c642324487d01f"), "name": "Kate Wills", "Job": "LISP Developer"}
> db.users.update (q,{$set: {job: ' Web Developer '}});
> Db.users.find (q);
{"_id": ObjectId ("5602bcd248c642324487d01f"), "job": "Web Developer", "name": "Kate Wills"}
> db.users.update (q,{$set: {email: ' [email protected] '}});
> Db.users.find (q);
{"_id": ObjectId ("5602bcd248c642324487d01f"), "email": "[email protected]", "Job": "Web Developer", "name": "Kate Wil LS "}
UNSET Remove a field
> db.users.update (q,{$unset: {job: "Web Developer"}});
> Db.users.find (q);
{"_id": ObjectId ("5602bcd248c642324487d01f"), "email": "[email protected]", "name": "Kate Wills"}
SAVE
> var bob = Db.users.findOne ({' Name.first ': ' Bob '});
Add a new Field
> bob.job = "Server Admin"
Save Record
> Db.users.save (Bob)
Findandmodify
Where new is set to True returns the changed value, set to False to return the value before the change
> db.users.findAndModify ({
... query:{name: "Kate Wills"},
... update:{$set: {age:20}},
... new:true});
{
"_id": ObjectId ("5602bcd248c642324487d01f"),
"Age": 20,
"Email": "[email protected]",
"Name": "Kate Wills"
}
$push Add Item
Db.links.update (n,{$push: {tags: ' blog '}});
$pushAll Add More Item
Db.links.update (n,{$pushAll: {tags: [' One ', ' both '}});
Unlike above, this will add children to the following
Db.links.update (n,{$push: {tags:[' one ', ' both '}});
$addToSet if the added item already exists, it is not added
Db.links.update (n,{$addToSet: {Tags: ' code '}});
Db.links.update (n,{$addToSet: {tags: {$each: [' One ', ' Four ']}});
$pull Removing item
Db.links.update (n,{$pull: {tags: ' four '}});
Remove Multiple item
Db.links.update (n,{$pullAll: {tags:[', ' Three '}});
Db.links.update (n,{$pull: {tags:[' one ', ' both '}});
Remove the first item or the last item
Db.links.update (n,{$pop: {tags:-1}});
Finding array-type subkeys requires the use of a location character
Db.users.update ({' logins.minutes ': 10},{$inc: {' logins.$.minutes ': 1}})
Db.users.update ({' logins.minutes ': 20},{$inc: {' logins.$.minutes ': 1}},false,true)
Db.users.update ({' logins.minutes ': 20},{$set: {random:true}},false,true)
Db.users.update ({' logins.minutes ': 20},{$set: {' logins.$.location ': ' Unknown '}},false,true)
Rename Field
Db.users.update ({random:true},{$rename: {' random ': ' Something_else '}},false,true);
Vii. deletion
Delete Users table
> Db.users.remove ();
Delete Name.first = John's record
> db.users.remove ({' Name.first ': "Bob"});
Delete the record and return
> db.users.findAndModify ({
... query:{' Name.first ':/b/},
... remove:true});
Delete a collections
> Db.other.insert ({name: "Andrew"});
> Show Collections
> Db.other.drop ();
Deleting a database
> Use other
> Db.test.insert ({});
> Show DBS
> DB
> Db.dropdatabase ()
> DB-You can see the other database at this point, but it's actually deleted, just in-memory
> Show DBS
Viii. Index
Note that MongoDB can use only one index for a query
Show Query Records
> Db.links.find ({title: ' nettuts+ '}). explain ();
The ID column is indexed by default
> Db.links.find ({"_id": ObjectId ("55f983616ffe01d4461ef22b")}). explain ();
Create an index
> Db.links.ensureIndex ({title:1});
Find Index
> Db.system.indexes.find ()
Some index-based parameters
Dropdups indicates that if there are duplicate values, only the first one is recorded
> Db.links.ensureIndex ({title:1},{unique:true, dropdups:true});
Sparse if there is no title field in the document is not included in the index
> Db.links.ensureIndex ({title:1},{unique:true, dropdups:true});
> Db.links.ensureIndex ({title:1},{sparse:true});
Combined index
> Db.links.ensureIndex ({title:1,url:1});
Delete Index
> Db.system.indexes.find ()
> Db.links.dropIndex ("Title_1")
Nine, in-depth study
1. MongoDB Official site
www.mongodb.org
2.10genEducation MongoDB Development leader, colleague provides training
Education.10gen.com
3. Several books
MongoDB The Definitive Guide
MongoDB in ACTION
MongoDB Developers
MongoDB Learning Notes