MongoDB Simple Instructions for use

Source: Internet
Author: User
Tags findone install mongodb


First install MongoDB
Software address
Https://www.mongodb.org/downloads#production;

Then locate the Bin folder in the MongoDB installation directory, go in its place, press shift+ right-click to open the command window here

My directory is C:\Program files\mongodb\server\3.0\bin


Then enter Mongod--dbpath=path in the command form
Path is the storage path to the database file must exist

Note: This command form cannot shut down this window is equivalent to stopping the MongoDB service

Open a command-line window under C:\Program files\mongodb\server\3.0\bin

Enter MONGO--host=127.0.0.1 in the command form or MONGO press ENTER

: The value after--host indicates the IP address of the server



Operations on a database
Use database name We just created the database person if not in the list, to display it, we need to insert some data into the person database
Db.person.insert ({name: "Zhangsan", age:30})
Show DNS See what database


View the database currently in use

DB or Db.getname ()

MongoDB Delete Database

Db.dropdatabase ();

MongoDB disconnects the connection to the MongoDB service
Exit
MongoDB View Command API


How the collection operates

View the Help API

Db.worker.help ()
See which collections are under the current database (collection)
Show collections

Create a Collection

Db.createcollection (collection_name) collection_name the name of the collection

Db.collection_Name.insert (document)

Db.collection_name.count () View collection there are several data
Db,collection_name.drop () Delete a collection from the current database


Inserting a document
Insert ()
Db.worker.insert ({name: ' zpx ', age:6})
Db.worker.insert ([{name: ' Wangwu ', age:50},{name: ' Xiaoming ', age:60}])
Add multiple [{name: ' Wangwu ', age:50},{name: ' Xiaoming ', age:60}] to the Worker collection

Save ()
Db.person.save ({name: "Xiaohong", age:50})
Db.person.save ({_id:objectid ("562c9caf671c978b6596e825"), Name: "Xiaohong", age:10})


Updates to Documents


Update ()
Db.collection.update (
<query>,
<update>,
{
Upsert: <boolean>
Multi: <boolean>
Writeconcern: <document>
}
)

The query:update query condition, similar to that in SQL Update query, is behind.
Update:update objects and some updated operators (such as $set, $inc ... ) and other $inc update $set directly after the original base.
Upsert: Optional, this parameter means that if there is no record of update, insert objnew,true as INSERT, default is False, do not insert.
Multi: Optional, mongodb default is False, only update the first record found, if this parameter is true, will be found on the condition of a number of records update all.
Writeconcern: Optional, throws an exception level

Db.worker.update ({name: ' liSi '},{$set: {name: ' Lisi_update '}}) modify the name of the data in the document data named LiSi to Lisi_update
Note: If you have more than one name, the data for Lisi is only updated

Db.worker.update ({name: ' Lisi_update '}, {$set: {age:40}},{multi:true}) modified the age of the data in the document name to be lisi_update to 40
Note: If more than one name is Lisi, this data is all updated


Db.person.update ({name: ' Pangzi '},{$inc: {age:1}}) adds 1 to the old age of the data in the document data name is Llisi_update



Deletion of documents

Remove ();
Db.collection.remove (
<query>,
<justOne>
)

If your MongoDB is after the 2.6 version, the syntax format is as follows:
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 is deleted.
Writeconcern: (optional) the level at which the exception is thrown.

Db.worker.remove ({name: ' Fjianzhou '}) removes all document data in the worker collection that name is Fjianzhou

Db.person.remove ({name: "Xiaohong"},1) removes the first data in the person collection that name is Xiaohong



Querying documents


Find ();

Db.worker.find ({},{age:1}) queries the specified column


Db.person.find (). Pretty (). Pretty () method to display all documents in a formatted manner.


Db.person.findOne () matches the first piece of data

Query condition operator

Db.person.find ({age:{$gt: 30}) data greater than 30

$GT >
$gte >=
$lt <
$lte <=
$ne! =

$in contains

Whether $exists exists

Using _id to query

Db.person.find (' _id ', ObjectId ());

Db.person.find (). Count () Number of bars
Query whether the value of a field contains another value

Db,person.find ({name:/pang/})

Beginning End
/^pang/
/pang$/

or condition Query


Db.person.find ({$or: [{key1:value},{},{}]})

OR and

Db.person.find (Key1:1,key2:2, $or: [])



Limit ();

Db.person.find (). Limit (2) query the first 2 data

Db.person.find (). Skip (2) Skip the first two data


Sort

Db.person.find (). Sort ({age:1}) Age ascending order









Installing Mongoose

NPM Install Mongoose


Reference Mongoose:

var mongoose = require ("Mongoose");

To connect to the database using "Mongoose":
var db = Mongoose.connect ("Mongodb://user:[email protected]:p ort/database");

Execute the following code to check the default database test, can the normal connection succeed?

For example
var mongoose = require ("Mongoose");
var db = Mongoose.connect ("mongodb://123.57.143.189:27017/zfpx");
Db.connection.on ("Error", function (Error) {
Console.log ("Database connection failed:" + error);
});
Db.connection.on ("Open", function () {
Console.log ("Database connection succeeded");
});


Schema
Define a model skeleton
var personschema = new Mongoose. Schema ({
Name: {type:string},
Age: {type:number, default:0},
Time: {type:date, Default:Date.now},
Email: {type:string,default: '}
});
The basic property types are: String, date, numeric, Boolean (Boolean), NULL, array, inline document, and so on.
String Date number Boolean Null Array

Create a model
var personmodel=db.model (' person ', personschema);

Note that mongoose will look for the plural collection of person in the database without looking for person

You can put him in the big picture.


Global. Model=function (ModName) {
Console.log (ModName)
Return Mongoose.model (ModName)
};

When you use it, if you want to update the data into the data, you need a new one if the query doesn't need it.
New Model (collection) (data)
user== data
Entity Save method
New Model (' user ') (user). Save (function (Err,user) {})

Save data
Model Save method
New Model (' User '). Create (User,function () {})
Querying data
Model (' User '). Find (User,function (err,doc) {})
Returns all records that contain only name, age two keys
Model (' user '). Find ({},{name:1, age:1, _id:0},function (Err,docs) {
Docs Query Result set
})
Model (' user '). FindOne ()
Model (' user '). FindByID ()
Model (' user '). Find ({name:{$exists: True}},function () {})//query All documents that exist with the name attribute

Data Update

Model (' User '). Update ({name: ' Junyu '},{$set: {name: ' Pangzi '}},function (err) {})//One
Model (' User '). Update ({name: ' Junyu '},{$set: {name: ' Pangzi '}},{multi:true},function (err) {})//All



Cursor operations



Model (' user '). Find ({},null,{limit:20},function () {})

Model (' user '). Find ({},null,{skip:20},function () {})

Model (' user '). Find ({},null,{sort:{age:-1}},function () {}) Descending








































MongoDB Simple Instructions for use

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.