MongoDB Database Basics

Source: Internet
Author: User
Tags delete key

1. Introduction:

MongoDB is a database based on distributed file storage. Written by the C + + language. Designed to provide scalable, high-performance data storage solutions for Web applications.
MongoDB is a product between a relational database and a non-relational database, and is the most versatile and most like relational database in a non-relational database. The data structure he supports is very loose and is a JSON-like Bson format, so you can store more complex data types. MONGO's biggest feature is that the query language he supports is very powerful, and its syntax is a bit like an object-oriented query language that almost implements most of the functionality of a relational database single-table query, and also supports indexing of data.

2. Features:

It is characterized by high performance, easy to deploy, easy to use, and easy to store data. The main features are:
For collection storage, easy to store data for object types.
mode is free, supports dynamic queries, supports full indexes, and contains internal objects. Support Queries. Supports replication and recovery. Use efficient binary data storage, including large objects such as video. Automatically handles fragmentation to support scalability at the cloud level. Supports multiple languages such as ruby,python,java,c++,php,c#. The file storage format is Bson (an extension of JSON). can be accessed over the network.
Specific introduction can be viewed Baidu Encyclopedia:
Http://baike.baidu.com/subview/3385614/9338179.htm#viewPageContent

3. Use:

(1) Installation:: https://www.mongodb.org/downloads, download suitable for their own development environment of the compression package, pressurized after the direct installation can be, very simple;
(2) Create a warehouse, log, new service: Create two folders in the installation directory DB, log; in cmd, enter the following command to create a warehouse, log, new service:
Mongod-dbpath "D:\study soft\mongodb\db"-logpath "D:\study soft\mongodb\log\mongodb.log"-install-servicename " MongoDB "
(3) using the Mongovue tool:
After downloading the installation (not introduced), in order to create a connection, it is generally only necessary to write the name (connection name) and server (address: localhost or 127.0.0.1):

After you've created it.

(4) Basic command:
--Create a collection:
Db.createcollection ("set name");
--Delete collection:
Db. Collection name. Drop ();
-Toggle Collection:
Use set name;
--Add Record:
Db. Set name. Insert ({"_id": 1001, "name": "yyy", "Sex": "F"});
--add more than one record to the collection
Db. Set name. Insert ([{"_id": 1003, "name": "Day SS Day", "Sex": "Male"},{"_id": 1004, "name": "tt", "Sex": "Male"}]);
-View the data in the collection:

    db.集合名.find()    db.集合名.findOne()    db.集合名.find({"_id":1001})      ---where key=val    db.集合名.find({"_id":{"gt":1001}})     ---where key>val    db.集合名.find({"_id":{"$lte":1001}})     ---where key<=val    db.集合名.find({"_id":{"$ne":1001}})     ---where key!=val

-$in in ...

    db.集合名  .find({"_id":{"$in":[1001,1002,1003]}})

-$or or

     db.集合名.find({"$or":[{"_id":1001},{"name":"haha"}]})

--$and and OR and ..... (Gender is male and ID 1009 or name is YC)

    db.zy.find({"sex":"男","$or":[{"_id":1009},{"name":"yc"}]})

-If there is a modification, does not exist then add
Db. Collection name. Save ({"_id": 1003, "name": "haha"});
-Modify
Db. Collection name. Update ({condition},{data to be modified});

--modifiers
$inc increase the corresponding value

    db.zy.insert({"_id":1004,"url":"www.baidu.com","pageViews":1});    db.zy.update({"_id":1004},{"$inc":{"pageViews":1}});        --将id为1004的文档中的pageViews键的值增加1

$set Modify the corresponding value

     db.zy.update({"_id":1002},{"name":"明明","sex":"女"})     db.zy.update({"_id":1002},{"$set":{"name":"明明","sex":"男"}})

--turn company into an array

    db.zy.insert({"_id":1005,"company":"yc","url":"www.baidu.com","pageViews":1});    db.zy.update({"_id":1005},{"$set":{"company":["yc","zy","nh"]}})

-delete key:

    db.zy.update({"_id":1005},{"$unset":{"company":1}})

-Array modifier:
$push add values to the array, duplicate values may occur

     db.zy.update({"_id":1005},{"$push":{"company":"hhh"}})

$each Loop Add

    db.zy.update({"_id":1005},{"$push":{"company":{"$each":["aa","bb","cc"]}}})

$SLICE Specifies the maximum length, its value must be negative, which means that the last N values are preserved

    db.zy.update({"_id":1005},{"$push":{"company":{"$each":["aa1","bb2","cc3"],"$slice":-10}}})

$pop Delete an element from the array key:1 from the end of the data delete key:-1 start with the head to delete

     db.zy.update({"_id":1005},{"$pop":{"company":1}})

$pull remove a matching value from the array

     db.zy.update({"_id":1005},{"$pull":{"company":"nh"}})

--Cycle

for( i=0;i<10;i++){        db.zy.insert({"_id":i,"name":i})    }  

Note: When _id is not inserted, MongoDB automatically assigns a Objectid
--Cursors

    var cursor =db.zy.find();    var obj;    while(cursor .hasNext()){        obj=cursor.next();        print(obj);    };    var cursor =db.zy.find();    cursor .forEach(function(x){        print(x);    })

– Paged Query

 db.zy.find().limit(3);  ---查前3条 db.zy.find().limit(3).skip(3);  ---跳过前3条,查后面的3条

– Sorting

    db.zy.find().sort({"_id":-1})       ---    1为升序   -1 为降序    db.zy.find().sort({"_id":-1,"name":1})   ---第一个相同就按第二个排序

eg

    db.zy.insert({        "_id":1006,        "content":"今天天气怎么样??",        "comments":[            {"comment":"好","count":0},            {"comment":"很好","count":0},            {"comment":"非常好","count":0},        ]    })

--access by array subscript

Db. Zy. Update({"_id":1006},{"$inc":{"Comments.1.count":1}}) DB. Zy. Update({"Comments.comment":"Very good"},{"$inc":{"Comments.$.count":1}})----match all the "good", so that its corresponding count+1Db. Zy. Update({"Comments.comment":"Very good"},{"$set":{"Comments.$.comment":"Great"}})----match all "very good" so that its corresponding value becomes super good

--mongodb default changes only one document at a time, if you need to change a number of satisfied records, you need to add the condition {multi:true} later

 Db.zy.update ({ "comments.comment" :  "very good" },{ " $inc  ": {" Comments.$.count ": 1 }},{ Multi:true }) db.zy.update ({ "comments.comment" :  "very good" },{ " $inc  ": {" Comments.$.count ": 1 }},< Span class= "hljs-literal" >false , true )  

(5). Data type:
null:{"x": null}
Boolean: {"X": True}
Value: {"X": 3.14} {"X": 3} numberint ("3") Numberlong ("3")
String: {"x": "Hello"}
Date: {"X": New Date ()}
Regular expression: {"X":/hello/ig}
Array: {"x": [All-in-all]}
Inline document: {"X": {"foo": {Bar}}}
Object ID: {"x": ObjectId ()}
Code: {"X": Function () {}}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

MongoDB Database Basics

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.