Mongodb基礎用法及查詢操作[轉載]

來源:互聯網
上載者:User

標籤:

插入多條測試資料
> for(i=1;i<=1000;i++){
... db.blog.insert({"title":i,"content":"mongodb測試文章。","name":"劉"+i});                                                      
... }

db.blog.list.find().limit(10).forEach(function(data){print("title:"+data.title);})   迴圈forEach 用法

 

db.blog.findOne();  取一條資料

db.blog.find();取多條資料
db.blog.remove(); 刪除資料集 
db.blog.drop();刪除表

刪除一個資料庫: 
1.use dbname 
2.db.dropDatabase()


======================================查詢操作=============================
db.blog.find() 相當於select * from blog 
db.blog.find({"age":27}) 相當於select * from blog where age=‘27‘
db.blog.find({"age":27,"name":"xing"}) 相當於select * from blog where age=‘27‘ and name="xing"
db.blog.find({},{"name":1}) select name from blog ,如果name:0則是不顯示name欄位
db.blog.find().limit(1) 相當於select * from blog limit 1

db.blog.find().sort({_id:-1}).limit(1)相當於select * from blog order by _id desc limit 1
db.blog.find().skip(10).limit(20) 相當於select * from blog limit 10,20
skip用的時候,一定要注意要是數量多的話skip就會變的很慢,所有的資料庫都存在此問題,可以不用skip進行分頁,用最後一條記錄做為條件
db.blog.find({"age":{"$gte":18,"$lte":30}})     select * from blog  where age>=27 and age<=50
$gt   >
$gte  >=
$lt   <
$lte  <=
$ne   !=
$in : in 
$nin: not in 
$all: all 
$not: 反匹配

查詢 creation_date > ‘2010-01-01‘ and creation_date <= ‘2010-12-31‘ 的資料 
db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});


db.blog.find().sort({_id:-1})  相當於select * from blog  order by _id desc  按_id倒序取資料  1為正序,多個條件用,號分開如{name:1,age:-1}
db.blog.find({"_id":{"$in",[12,3,100]}})  相當於select * from blog where _id in (12,3,100)
db.blog.find({"_id":{"$nin",[12,3,100]}})  相當於select * from blog where _id not in (12,3,100)
db.blog.find({"$or":[{"age":16},{"name":"xing"}]}) 相當於select * from blog where age = 16 or name = ‘xing‘
db.blog.find({"id_num":{"$mod":[5,1]}}) 取的是id_num mod 5 = 1 的欄位,如id_num=1,6,11,16
db.blog.find({"id_num":{"$not":{"$mod":[5,1]}}}) 取的是id_num mod 5 != 1 的欄位,如除了id_num=1,6,11,16等所有欄位,多於正則一起用

$exists判斷欄位是否存在

db.blog.find({ a : { $exists : true }}); // 如果存在元素a,就返回
db.blog.find({ a : { $exists : false }}); // 如果不存在元素a,就返回


$type判斷欄位類型 
查詢所有name欄位是字元類型的 
db.users.find({name: {$type: 2}}); 
查詢所有age欄位是整型的 
db.users.find({age: {$type: 16}}); 


db.blog.find({"z":null}) 返回沒有z欄位的所有記錄
db.blog.find({"name":/^joe/i}) 尋找name=joe的所有記錄,不區分大小寫

db.blog.distinct(‘content‘)  查指定的列,並去重


查詢數組
db.blog.find({"fruit":{"$all":["蘋果","桃子","梨"]}})   fruit中必需有數組中的每一個才符合結果
db.blog.find({"fruit":{"$size":3}})  fruit數組長度為3的符合結果
db.blog.find({"$push":{"fruit":"桔子"}})相當於db.blog.find({"$push":{"fruit":"桔子"},"$inc":{"size":1}})
$slice 可以按位移量返回記錄,針對數組。如{"$slice":10}返回前10條,{"$slice":{[23,10]}}從24條取10條
如果對象有一個元素是數組,那麼$elemMatch可以匹配內數組內的元素

db.people.find({"name.first":"joe","name.last":"schmoe"}) 子查詢如:{"id":34,"name":{"first":"joe","last":"schmoe"}}

db.blog.find({"comments":{"$elemMatch":{"author":"joe","score":{"$gte":5}}}}) 查joe發表的5分以上的評論,注意comments為二維數組
$where 在走投無路的時候可以用,但它的效率是很低的。


遊標用法
cursor.hasNext()檢查是否有後續結果存在,然後用cursor.next()將其獲得。
>while(cursor.hasNext()){
   var obj = cursor.next();
   //do same
}

 

 

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ConditionalOperators%3A%3C%2C%3C%3D%2C%3E%2C%3E%3D 手冊

 

> use blog
> db.blog.insert({"title":"華夏之星的部落格","content":"mongodb測試文章。"});
> db.blog.find();
{ "_id" : ObjectId("4e29fd262ed6910732fa61df"), "title" : "華夏之星的部落格", "content" : "mongodb測試文章。" }
> db.blog.update({title:"華夏之星的部落格"},{"author":"星星","content":"測試更新"});
> db.blog.find();
{ "_id" : ObjectId("4e29fd262ed6910732fa61df"), "author" : "星星", "content" : "測試更新" }

 


 db.blog.insert不帶括弧則顯示源碼
db.blog.insert();插入
db.blog.update();更新

> db.blog.update({title:"華夏之星的部落格"},{"author":"星星","content":"測試更新"});

update預設情況下只能對合格第一個文檔執行操作,要使所有的匹配的文檔都得到更新,可以設定第四個參數為 true

> db.blog.update({title:"華夏之星的部落格"},{"author":"星星","content":"測試更新"},false,true);

> db.runCommand({getLastError:1}) 可以查看更新了幾條資訊,n就是條數

 

 備份blog資料庫到/soft目錄
/usr/local/webserver/mongodb/bin/mongodump -d blog -o /soft

還原資料庫

/usr/local/webserver/mongodb/bin/mongorestore -d blog -c blog   /soft/blog/blog.bson

 

匯出資料庫(備份出來的資料是二進位的,已經經過壓縮。)
/usr/local/webserver/mongodb/bin/mongodump -h 127.0.0.1 -port 27017 -d demo -o /tmp/demo
匯入資料
/usr/local/webserver/mongodb/bin/mongorestore -h 127.0.0.1  -port 27017 --directoryperdb /tmp/demo


5) $all
$all和$in類似,但是他需要匹配條件內所有的值:
如有一個對象:
{ a: [ 1, 2, 3 ] }

下面這個條件是可以匹配的:

db.things.find( { a: { $all: [ 2, 3 ] } } );

但是下面這個條件就不行了:

db.things.find( { a: { $all: [ 2, 3, 4 ] } } );6) $size
$size是匹配數組內的元素數量的,如有一個對象:{a:["foo"]},他只有一個元素:
下面的語句就可以匹配:db.things.find( { a : { $size: 1 } } );

官網上說不能用來匹配一個範圍內的元素,如果想找$size<5之類的,他們建議建立一個欄位來儲存元素的數量。

 

8) $type

$type 基於 bson type來匹配一個元素的類型,像是按照類型ID來匹配,不過我沒找到bson類型和id對照表。

db.things.find( { a : { $type : 2 } } ); // matches if a is a string
db.things.find( { a : { $type : 16 } } ); // matches if a is an int
9)Regex
mongo支援Regex,如:
db.customers.find( { name : /acme.*corp/i } ); // 後面的i的意思是區分大小寫10) 查詢資料內的值
下面的查詢是查詢colors內red的記錄,如果colors元素是一個資料,資料庫將遍曆這個數組的元素來查詢。db.things.find( { colors : "red" } );
11) $elemMatch
如果對象有一個元素是數組,那麼$elemMatch可以匹配內數組內的元素:
> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) 
{ "_id" : ObjectId("4b5783300334000000000aa9"), 
"x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
}$elemMatch : { a : 1, b : { $gt : 1 } } 所有的條件都要匹配上才行。

注意,上面的語句和下面是不一樣的。

> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
$elemMatch是匹配{ "a" : 1, "b" : 3 },而後面一句是匹配{ "b" : 99 }, { "a" : 11 } 
12) 查詢內嵌物件的值
db.postings.find( { "author.name" : "joe" } );

注意用法是author.name,用一個點就行了。更詳細的可以看這個連結: dot notation

舉個例子:

> db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})

如果我們要查詢 authors name 是Jane的, 我們可以這樣:

> db.blog.findOne({"author.name" : "Jane"})

 

 

 

 

 


mongodb目前沒有或(or)操作符,只能用變通的辦法代替,可以參考下面的連結:

http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions

http://www.bumao.com/index.php/mongo_and_php

 

Mongodb基礎用法及查詢操作[轉載]

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.