MongoDB step by step (二)mongodb 與 T-SQL 對比,mongodbt-sql

來源:互聯網
上載者:User

MongoDB step by step (二)mongodb 與 T-SQL 對比,mongodbt-sql



SQL Terms/Concepts

MongoDB Terms/Concepts

database

database

table

Collection(集合)

row

document(文檔)

column

Key(鍵)

Value

Value(值)

index

index

table joins

embedded documents and linking

primary key

primary key

Specify any unique column or column combination as primary key.

In MongoDB, the primary key is automatically set to the _id field.

aggregation (e.g. group by)

aggregation pipeline

















Help

查看協助(mongodb 中注意大小寫)

db.help()

help on db methods

db.mycoll.help()

help on collection methods

sh.help()

sharding helpers

rs.help()

replica set helpers

help admin

administrative help

help connect

connecting to a db help

help keys

key shortcuts

help misc

misc things to know

help mr

mapreduce

show dbs

show database names

show collections

show collections in current database

show users

show users in current database

show profile

show most recent system.profile entries with time >= 1ms

show logs

show the accessible logger names

show log [name]

prints out the last segment of log in memory, 'global' is default

use <db_name>

set current database

db.foo.find()

list objects in collection foo

db.foo.find( { a : 1 } )

list objects in foo where a == 1

it

result of the last line evaluated; use to further iterate

DBQuery.shellBatchSize = x

set default number of items to display on shell

exit

quit the mongo shell



                                                                                                            資料庫

show dbs

查看所有資料庫

use mydb

設定為當前資料庫

db

查看當前資料庫名稱

db.createCollection("tab")

db.tab.insert({"id":1})

建立資料庫(建立collection)

建立資料庫(插入資料也會被建立)

db.copyDatabase("mydb", "newmydb", "127.0.0.1")

複製為另一個新的資料庫

db.dropDatabase()

刪除資料庫



Collection定義操作(集合必須以字母或底線開頭)

db.createCollection("tab",{size:1024,max:1000,capped:true})

db.tab.insert({"id":1})

建立collections 並做限制(如建立“tab”)

(插入資料也會建立collections)

show collections

查看當前資料庫所有collections

db.tab.drop()

刪除collections

db.tab.update({},{$rename:{"name":"newname"}},false,true)

更改所有行的欄位名name為newname

db.getCollection('tab').renameCollection('newtab')

db.newtab.renameCollection('tab')

更改collection名稱



Collection 資料操作

db.tab.save({"id":2})

db.tab.insert({"id":3})

db.tab.insert([{ size: "S", qty: 25 }, { size: "M", qty: 50 }])

db.tab.insert({ array :[{ size: "S", qty: 25 }, { size: "M", qty: 50 } ]})

插入資料到collections

(會自動產生唯一列 “_id”)

插入多行(相當: insert into tab values(“S”,1), (“M”,50))

欄位中插入子集

db.tab.update({"id":1},{$set:{"id":5}})

更改資料(id值由1更改為5)

db.tab.update({ id:2},{id:6, name:'E'})

將id=2的行更新為新的行

db.tab.update({"id":1},{$unset:{ name:'120'}})

刪除一個鍵值對(刪除id=2中的欄位name)

db.tab.update({"id":1},{$push:{ name:'C'}})

往id=1的行 欄位為name數組中插入元素’C’

db.tab.update({"id":1},{$pull:{ name:'C'}})

從id=1的行 欄位為name數組中刪除所有元素’C’

db.tab.remove({"id":3})

db.tab.remove({"id":3},1)

db.tab.remove({})

刪除id=3的所有記錄

刪除id=3的第一條記錄

刪除所有記錄




Collection查詢資料操作

Select * from tab

db.tab.find()

db.tab.find({})

Select id from tab

db.tab.find({},{"id":1})   #({條件},{欄位:0/1})

db.tab.find({},{"_id":0,"id":1})

db.tab.aggregate({ $project : {id : 1 }});

db.tab.find({id:{$exists:1}});

Select * from tab where id=1

db.tab.find( { id :1})

Select id from tab where id=1

db.tab.find({id :1},{"_id":0,"id":1})

Select * from tab where id<>1

db.tab.find({id:{$ne:1}})

Select * from tab where id>2

db.tab.find( { id: { $gt: 2} } )

Select * from tab where id<3

db.tab.find( { id: { $lt: 3} } )

Select * from tab where id>=2

db.tab.find( { id: { $gte: 2 } } )

Select * from tab where id<=3

db.tab.find( { id: { $lte: 3} } )

Select * from tab where id = 1 or id = 2

db.tab.find({$or:[{id:3},{id:2}]})

Select * from tab where id < 2 or id >4

db.tab.find({$or:[{id:{$gt:4}},{id:{$lt:2}}]})

Select * from tab where id in (1,2)

db.tab.find( { id: { $in: [ 1, 2 ] } } )

Select * from tab where id not in (2,3)

db.tab.find({id:{"$nin":[2,3]}})

Select * from tab where id between 2 and 3

Select * from tab where id >= 2 and id <= 3

db.tab.find({$and:[{id:{$gte:2}},{id:{$lte:5}}]})

Select * from tab where id = 1 and name = ‘kk’

db.tab.find({id:2, name:'kk'})

Select distinct id from tab

db.tab.distinct("id");

db.runCommand ( { distinct: "tab", key: "id" } )

Select distinct id from tab where name = ‘A’

db.runCommand({distinct:'tab',key:'id',query:{name:'A'}})

Select * from tab where name like ‘%A%’

db.tab.find({ name:{$regex:"A"}})

db.tab.find({ name:/A/})

Select * from tab order by id asc

db.tab.find().sort({id:1})

Select * from tab order by id desc

db.tab.find().sort({id:-1})

Select  top 5 * from tab

db.tab.find().limit(5)

跳過前m條記

db.tab.find().skip(2)

db.tab.aggregate({ $skip : 2 });

跳過前m條記錄,從m+1開始取n條

db.tab.find().skip(2).limit(3)

除了指定的列,其他列都顯示

db.tab.find({id:null})

db.tab.find({},{"_id":0})

尋找欄位id為string類型的行(參考下表格)

db.tab.find({ id: {$type: 2}});

 

 

select name,sum(id) as sumid

from tab

where id >0 group by name

db.tab.group({

key:{ "name":true}  # group by name

,cond:{id:{ $gt:0}}   # where id >0

,reduce:function(obj,prev) #彙總函式

{ prev.sumid += obj.id; } #函數邏輯,累加id

, initial: {sumid: 0 }})  #初始化

Select sum(*) from tab

db.tab.group({key:{},cond:{}

,reduce:function(obj,prev)

{ prev.sumid += obj.id; },initial: {sumid: 0 }});

Select sum(*) as newcol from tab

db.tab.aggregate([{$group:{_id:"$by_user",newcol:{$sum:"$id"}}}])

Select count(*) from tab

db.tab.count()  或者 db.tab.find().count()

Select count(*) from tab

db.tab.group({key:{},cond:{},

reduce:function(obj,prev)

{ prev.sumid += 1; },initial: {sumid: 0 }});

Select avg(*) from tab

db.tab.aggregate([{$group:{_id:"$by_user",newcol:{$avg:"$id"}}}])

Select max(*) from tab

db.tab.find().sort({id:-1}).limit(1)

db.tab.aggregate([{$group:{_id:"$by_user",newcol:{$max:"$id"}}}])

Select min(*) from tab

db.tab.find().sort({id:1}).limit(1)

db.tab.aggregate([{$group:{_id:"$by_user",newcol:{$min:"$id"}}}])

 

 

#元素查詢

#db.tab.insert({ratings: [ 5, 8, 9 ] })

db.tab.find({ ratings: [ 5, 8, 9 ] } )   #尋找匹配的數組

db.tab.find({ ratings: 5 })     #尋找元素中含“5”的記錄

db.tab.find({ ratings:{$elemMatch:{$gt:8,$lt:10}}})   #元素匹配尋找

#內嵌文檔

#db.tab.insert({producer:{company: 'ABC',address: 'Street'}})

#db.tab.insert({producer:[{ company: 'ABC',address: 'Street'},{ company: 'KK',address: 'Street2'}] })

db.tab.find({producer:{company: 'ABC',address: 'Street'}})

db.tab.find({'producer.company': 'ABC'})

db.tab.find( { 'producer.0.address': 'Street'} )  #欄位'producer的第一個元素的address=’ Street’


類型描述

類型值

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



相關文章

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.