MongoDB - basic
mongoDB basic
from:http://www.tutorialspoint.com/mongodb
prject:https://github.com/chenxing12/l4mongodb
Overview
MongoDB is a cross-platform, document oriented database that provides, high
performance, high availability, and easy scalability. MongoDB works on concept
of collection and document.
Database
Database is a physical container for collections. Each database gets its own set
of files on the file system. A single MongoDB server typically has multiple
databases.
Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS
table. A collection exists within a single database. Collections do not enforce
a schema. Documents with a collection can have different fields. Typically, all
documents in a collection are of similar or related purpose.
Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic
schema means that documents in the same collection do not need to have the same
set of fields or structure, and common fields in a collection's documents may
hold different types of data.
Below given table shows the relationship of RDBMS terminology with MongoDB
RDBMS | MongoDB |
---|---|
Database | Database |
Table | Collection |
Tuple/Row | Document |
column | Field |
Table Join | Embedded Documents |
Table Join | Primary Key(Default key _id provided by mongodb itself) |
Sample document
Below given example shows the document structure of a blog site which is simply
a comma separated key value pair.
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}
]
}
Getting-Start
Database
check all the databases:
> show dbs
local 0.000GB
mrf 0.000GB
test 0.005GB
create database: for example create mydb
> use mydb
switched to db mydb
> show dbs
local 0.000GB
mrf 0.000GB
test 0.005GB
The database mydb has not been created, because the db is empty,
You must create at lest one collection next.For example:
>
> use mydb
switched to db mydb
> show dbs
local 0.000GB
mrf 0.000GB
test 0.005GB
>
> show collections
> db.user.insert({name:"Ryan"})
WriteResult({ "nInserted" : 1 })
> show dbs
local 0.000GB
mrf 0.000GB
mydb 0.000GB
test 0.005GB
check current database:
> db
mydb
switch db:
> db
mydb
> use test
switched to db test
> db
test
drop database:
> show dbs
local 0.000GB
mrf 0.000GB
mydb 0.000GB
test 0.005GB
> use mydb
switched to db mydb
> db.dropDatabase()
{ "dropped" : "mydb", "ok" : 1 }
> show dbs;
local 0.000GB
mrf 0.000GB
test 0.005GB
collection
create collection
when you insert data, if the collection not exists, it will be created automatically:
> show collections
restaurants
test
> db.mycollection.insert({name:"test"})
WriteResult({ "nInserted" : 1 })
> show collections
mycollection
restaurants
test
Of course, there is other way to create a specify collection:
Syntax
Basic syntax of createCollection() command is as follows:
db.createCollection(name, options)
In the command, name
is the name of collection created, Options
is a document
and used to specify configuration of collection.
Options
parameter is optional, so you need to specify only name of the collection.
Following is the list of options you can use:
Filed | Type | Description |
---|---|---|
capped | Boolean | (Optional) If true, enables a capped collection. Capped collection is a collection fixed size collection that automatically overwrites its oldest entries when it reaches its maximum size. If you sepecify true, you need specify size parameter too |
autoIndexID | Boolean | (Optional) If true, automatically create index on _id filed. Default value is false |
size | number | (Optional) Specify a maximum size in bytes for a capped collection. If capped is true, then you need specify this filed also |
max | number | (Optional) Specifies the maximum number of documents allowed in the capped collection. |
while inserting the document , MongoDB first checks size filed of capped collection, then it checks max filed.
Example
> db.mycollection.drop()
true
> show collections
restaurants
test
>
>
> db.createCollection("mycollection")
{ "ok" : 1 }
> show collections
mycollection
restaurants
test
>
> db.createCollection("mycol",{capped:true,autoIndexID:true,size:6142800, max:10000})
{ "ok" : 1 }
> show collections
mycol
mycollection
restaurants
test
>
drop()
> use test
switched to db test
> show collections
mycol
mycollection
restaurants
test
> db.mycol.drop()
true
> show collections
mycollection
restaurants
test
DataType
MongoDB supports many datatypes whose list is given below:
String : This is most commonly used datatype to store the data. String in mongodb must be UTF-8 valid.
Integer : This type is used to store a numerical value. Integer can be 32 bit or 64 bit depending upon your server.
Boolean : This type is used to store a boolean (true/ false) value.
Double : This type is used to store floating point values.
Min/ Max keys
: This type is used to compare a value against the lowest and highest BSON elements.
Arrays : This type is used to store arrays or list or multiple values into one key.
Timestamp : ctimestamp. This can be handy for recording when a document has been modified or added.
Object : This datatype is used for embedded documents.
Null : This type is used to store a Null value.
Symbol : This datatype is used identically to a string however, it's generally reserved for languages that use a specific symbol type.
Date : This datatype is used to store the current date or time in UNIX time format. You can specify your own date time by creating object of Date and passing day, month, year into it.
Object ID: This datatype is used to store the document’s ID.
Binary data : This datatype is used to store binay data.
Code : This datatype is used to store javascript code into document.
Regular expression : This datatype is used to store regular expression
Insert
MongoDB insert option:
> show dbs;
local 0.000GB
mrf 0.000GB
test 0.005GB
> use test
switched to db test
> show collections;
mycollection
restaurants
test
>
>
> db.mycollection.insert({
title:"MongoDB Overview",
description:'MongoDB is no sql database',
by:'tutorials point',
url:'http://www.tutorialspoint.com',
tags:['mongodb','database','NoSQL'],
likes:100
})
WriteResult({ "nInserted" : 1 })
>
> db.mycollection.find()
{ "_id" : ObjectId("577e0dce99da0904659393c0"), "title" : "MongoDB Overview", "description" : "MongoDB is no sql databas
e", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "lik
es" : 100 }
> db.mycollection.find().pretty()
{
"_id" : ObjectId("577e0dce99da0904659393c0"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
>
Here mycollections
is our collection name, as created in previous tutorial. If the
collection doesn't exist in the database, then MongoDB will create this collection
adn then insert document into it.
In the inserted document if we don't specify the _id
parameter, then MongoDB
assigns an unique ObjectId for this document.
_id
is 12 bytes hexadecimal number unique for every document in a collection.
12 Bytes are dived as follows :
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
To insert multiple documents in single query, you can pass an array of documents
in insert() command.
Example
db.post.insert([
{
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
},
{
title: 'NoSQL Database',
description: 'NoSQL database doesn\'t have tables',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 20,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
]
}
])
find()
The find() Method
To query data from MongoDB collection, you need to user MongoDB's find()
method.
Syntax
Basic syntax of find() method id as follows:
db.collection_name.find()
find()
method will display all the documents in a non structured way.
The pretty() Method
To display the results in a formatted way, you can use pretty()
method.
db.collection_name.find().pretty()
Example
> show collections
mycollection
post
restaurants
test
> db.post.find().pretty()
{
"_id" : ObjectId("577e11fd502847799b05f062"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("577e11fd502847799b05f063"),
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T10:35:00Z"),
"like" : 0
}
]
}
>
RDBMS Where Clause Equivalents in MongoDB
To query the document on the basis of some codition, you can use following
options:
Options | Syntax | Example | RDBMS Equivalent |
---|---|---|---|
Equal | {<key>:<value>} | db.mycol.find({'by':'abc'}).pretty() | where by='abc' |
Less Than | {<key>:{$lt:<value>}} | db.mycol.find({'likes':{$lt:50}}).pretty() | where likes < 50 |
Less Than Equals | {<key>:{$lte:<value>}} | db.mycol.find({'likes':{$lte:50}}).pretty() | where likes <= 50 |
Greater Than | {<key>:{$gt:<value>}} | db.mycol.find({'likes':{$gt:50}}).pretty() | where likes > 50 |
Greater Than Equals | {<key>:{$gte:<value>}} | db.mycol.find({'likes':{$gte:50}}).pretty() | where likes >= 50 |
Not Equals | {<key>:{$ne:<value>}} | db.mycol.find({'likes':{$ne:50}}).pretty() | where likes != 50 |
Example
> db.mycol.find().pretty()
{
"_id" : ObjectId("577e19c5502847799b05f064"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("577e19c5502847799b05f065"),
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T10:35:00Z"),
"like" : 0
}
]
}
>
> db.mycol.find({'likes':{$gt:50}}).pretty()
{
"_id" : ObjectId("577e19c5502847799b05f064"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
> db.mycol.find({'likes':{$lt:50}}).pretty()
{
"_id" : ObjectId("577e19c5502847799b05f065"),
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T10:35:00Z"),
"like" : 0
}
]
}
AND in MongoDB
Syntax
In the find()
method if you pass multiple keys by separating them by ',
' then
MongoDB treats it AND
condition. Basic syntax of AND
is shown below:
db.mycol.find({ keys:value, key2:value2 }).pretty()
Example:
Below given example will show all the tutorials written by and
whose title is 'MongoDB OVerview':
> db.mycol.find({"by":"tutorials point","title":"MongoDB Overview"}).pretty()
{
"_id" : ObjectId("577e19c5502847799b05f064"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
For the above given example equivalent where clause will be
where by='tutorials point' AND title = 'MongoDB Overview'
.
You can pass any number of key, value pairs in find clause.
OR in MongoDB
Syntax
To query documents based on the OR condition, you need to use $or
keyword.
Basic syntax of OR is shown below −
>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
> db.mycol.find(
{
$or:[
{"title":"MongoDB Overview"},{"likes":20}
]
}).pretty()
{
"_id" : ObjectId("577e19c5502847799b05f064"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("577e19c5502847799b05f065"),
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T10:35:00Z"),
"like" : 0
}
]
}
Using AND and OR together
Example
Below given example will show the documents that have likes greater than 10
and whose title is either 'MongoDB Overview' or by is 'tutorials point':
Equals:where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')
> db.mycol.find({
"likes": {$gt:10},
$or: [
{"by": "tutorials point"}, {"title": "MongoDB Overview"}
]
}).pretty()
{
"_id" : ObjectId("577e19c5502847799b05f064"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no sql database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("577e19c5502847799b05f065"),
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-10T10:35:00Z"),
"like" : 0
}
]
}
MongoDB - basic的更多相关文章
- DB Intro - MongoDB Basic
mongoDB basic from:http://www.tutorialspoint.com/mongodb prject:https://github.com/chenxing12/l4mong ...
- [AWS] Deploy react project on EC2
如何在aws部署项目 申请到亚马逊AWS免费账户后,我们可以拥有很多的免费云服务产品项目,其中包括: EC2云服务器. Amazon S3存储. Amazon RDS数据库. Amazon Cloud ...
- MongoDB-2.6.0 (OpenLogic CentOS7.2)
平台: CentOS 类型: 虚拟机镜像 软件包: mongodb basic software database linux open source 服务优惠价: 按服务商许可协议 云服务器费用:查 ...
- basic mongodb
basic mongodb */--> pre { background-color: #2f4f4f;line-height: 1.6; FONT: 10.5pt Consola," ...
- lbs basic mongodb
MongoDB地理位置索引常用的有两种. db.places.ensureIndex({'coordinate':'2d'}) db.places.ensureIndex({'coordinate': ...
- 【MongoDB】The basic operation of Index in MongoDB
In the past four blogs, we attached importance to the index, including description and comparison wi ...
- MySQL、MongoDB、Redis数据库Docker镜像制作
MySQL.MongoDB.Redis数据库Docker镜像制作 在多台主机上进行数据库部署时,如果使用传统的MySQL的交互式的安装方式将会重复很多遍.如果做成镜像,那么我们只需要make once ...
- 搭建高可用mongodb集群(三)—— 深入副本集内部机制
在上一篇文章<搭建高可用mongodb集群(二)—— 副本集> 介绍了副本集的配置,这篇文章深入研究一下副本集的内部机制.还是带着副本集的问题来看吧! 副本集故障转移,主节点是如何选举的? ...
- Mongodb源代码阅读笔记:Journal机制
Mongodb源代码阅读笔记:Journal机制 Mongodb源代码阅读笔记:Journal机制 涉及的文件 一些说明 PREPLOGBUFFER WRITETOJOURNAL WRITETODAT ...
随机推荐
- jquery 中的框架
DWZ 国产Ajax RIA开源框架 Ninja UI 框架 提供页面插件 angela ui框架 表单布局等 Chico UI 快速页面布局 PrimeUI w2ui 布局 ...
- 剑指Offer面试题:14.链表的倒数第k个节点
PS:这是一道出境率极高的题目,记得去年参加校园招聘时我看到了3次,但是每次写的都不完善. 一.题目:链表的倒数第k个节点 题目:输入一个链表,输出该链表中倒数第k个结点.为了符合大多数人的习惯,本题 ...
- 新人入职100天,聊聊自己的经验&教训
这篇文章讲了什么? 如题,本屌入职100天之后的经验和教训,具体包含: 对开发的一点感悟. 对如何提问的一点见解. 对Google开发流程的吐槽. 如果你 打算去国外工作. 对Google的开发流程感 ...
- 《JavaScript语言精粹》—— 读书总结
话说这本书还是同学的推荐才读的,之前感觉这本书太薄了,不值得看,没想到小身材有大智慧,书中的内容总结的还是很到位的!所以就把最后几章,精华的部分整理整理. 优美的特性 函数是顶级对象 在JS中,没有块 ...
- C#事件
事件(event),这个词儿对于初学者来说,往往总是显得有些神秘,不易弄懂.而这些东西却往往又是编程中常用且非常重要的东西.大家都知道windows消息处理机制的重要,其实C#事件就是基于window ...
- Oralce 重建EM服务,OracleDBConsoleOracle
今天打开Oracle ,想进em看看,结果发现OracleDBConsoleOracle服务老是报错: OracleDBConsoleOracle 服务因 2 (0x2) 服务性错误而停止. 搞不懂, ...
- iOS-即时通讯-环信
下载地址:http://www.easemob.com/downloads SDK目录讲解 1.从官网下载下来的包分为如下四部分: 环信iOS SDK 开发使用 环信iOS release note ...
- Ubuntu14.04、win7双系统如何设置win7为默认启动项
Ubuntu14.04.win7双系统如何设置win7为默认启动项 Ubuntu14.04.win7双系统设置win7为默认启动项方法: 在启动项选择菜单处记住windows 7对应的序号. 从上至下 ...
- KnockoutJS 3.X API 第七章 其他技术(8) 异步错误处理
注意:本文档适用于Knockout 3.4.0及更高版本. ko.onError Knockout包装内部异步调用,并在抛出原始错误之前查找可选的ko.onError回调以执行(如果遇到异常). 这使 ...
- canvas绘图、WebGL、SVG
目录 一.Canvas 1.1.创建canvas元素 1.2.画线 1.3.绘制矩形 1.4.绘制圆弧 1.5.绘制图像 1.6.绘制文字 1.7.随机颜色与简单动画 二.WebGL 2.1.HTML ...