mongoDB shell中管理數據庫和集合、在集合中查找文檔

1、Database對象,Collection對象

  • 創建Connection對象

mongo(host:port)

如連接到本地主機的mongodb服務器,並創建一個Connection對象

var myConn = new Mongo("localhost");
  • 創建Database對象:
>use test
>db.getName()

或者使用Connection對象的方法getDB()

mongo = new Mongo("localhost");

newDB = mongo.getDB("newDB");

newDB.getName();
  •  創建Collection對象
//顯示集合myCollection的統計信息
db.myCollection.stats()

或者使用Database對象的getCollection()

mycoll = db.getCollection("myCollection");
mycoll.stats();

2、管理數據庫

  • 顯示數據庫列表:
show dbs
  • 切換到其他數據庫:
use testDB

//或者

db = db.getSiblingDB('testDB');
  •  創建數據庫,添加集合或者用戶時隱式創建
use newDB
db.createCollection("newCollection")

或者:

mongo = new Mongo("localhost");
db = mongo.getDB("test");
db.createCollection("newCollection");
  •  刪除數據庫
use newSB
db.dropDatabase()

 dropDatabase()不會刪除當前數據庫柄,若刪除後沒有切換到其他數據庫創建集合,那麼會重新創建被刪除的數據庫。

或者使用JavaScript腳本刪除數據庫:

mongo = new Mongo("localhost");
mydb = mongo.getDB("newDB");
mydb.dropDatabase();

3、管理集合

  • 顯示數據庫集合列表
use test
show collections

或者使用Database對象的getCollectionNames()

use test
collectionNames = db.getCollectionNames()
  •  創建集合:
use testDB
db.createCollection("newCollection")
  • 刪除集合
use testDB
db.newCollection.drop()

或者:

use testDB
coll = db.getCollection("newCollection")
coll.drop()

4、從集合中獲取文檔

Cursor對象:

Cursor對象相當於一個指針,可用它來迭代訪問數據庫中的一組對象,如,使用find()時,返回的就是就是一個Cursor對象,而非實際的文檔。

這個對象有很多方法,如count()  forEach(function)  hasNext()  map(function) 等。具體要查詢API。

有些操作允許指定query參數,這個參數對Cursor對象返回的文檔進行限制。它的屬性稱爲運算符。

一些常用的運算符有:$gt $in $size $or $and $not等等。具體查詢API。

Collection 對象的方法:

find(query,projection) 返回與查詢條件匹配的文檔。

findOne(query,projection)返回與查詢條件匹配的第一個文檔。

query即是query參數,包含運算符,projection指定返回的文檔應包含哪些字段。

查找單個文檔:

mongo = new Mongo("localhost");
wordsDB = mongo.getDB("words");
wordsColl = wordsDB.getCollection("word_stats");
word = wordsColl.findOne();
print("Single Document: ");
printjson(word);

查找多個文檔:

mongo = new Mongo("localhost");
wordsDB = mongo.getDB("words");
wordsColl = wordsDB.getCollection("word_stats");
print("\nFor Each List: ");
cursor = wordsColl.find().limit(10);
cursor.forEach(function(word){
  print("word: " + word.word);
});
print("\nMapped Array: ");
cursor = wordsColl.find().limit(10);
words = cursor.map(function(word){
  return word.word;
});
printjson(words);
print("\nIndexed Docuemnt in Array: ");
cursor = wordsColl.find();
words = cursor.toArray();
print(JSON.stringify(words[55]));
print("\nNext Document in Cursor: ");
cursor = wordsColl.find();
word = cursor.next();
print(JSON.stringify(word));

查找特定的文檔:

function displayWords(msg, cursor, pretty){
  print("\n"+msg);
  words = cursor.map(function(word){
    return word.word;
  });
  wordStr = JSON.stringify(words);
  if (wordStr.length > 65){
    wordStr = wordStr.slice(0, 50) + "...";
  }
  print(wordStr);
}
mongo = new Mongo("localhost");
wordsDB = mongo.getDB("words");
wordsColl = wordsDB.getCollection("word_stats");

//查找字段first以a,b,c開頭的單詞
cursor = wordsColl.find({first: {$in: ['a', 'b', 'c']}});
displayWords("Words starting with a, b or c: ", cursor);

//查找size字段大於12的文檔
cursor = wordsColl.find({size:{$gt: 12}});
displayWords("Words longer than 12 characters: ", cursor);

//查找size字段除2餘數爲0的文檔
cursor = wordsColl.find({size:{$mod: [2,0]}});
displayWords("Words with even Lengths: ", cursor);

//查找數組字段letters包含12個字母的單詞
cursor = wordsColl.find({letters:{$size: 12}});
displayWords("Words with 12 Distinct characters: ", cursor);

cursor = wordsColl.find({$and: 
                           [{first:{
                              $in: ['a', 'e', 'i', 'o', 'o']}},
                            {last:{
                              $in: ['a', 'e', 'i', 'o', 'o']}}]});
displayWords("Words that start and end with a vowel: ", cursor);

//子文檔stats的字段vowels值大於5
cursor = wordsColl.find({"stats.vowels":{$gt: 5}});
displayWords("Words containing 6 or more vowels: ", cursor);

//查找包含全部5個元音字母的單詞
cursor = wordsColl.find({letters:{$all: ['a','e','i','o','u']}});
displayWords("Words with all 5 vowels: ", cursor);

//查找包含非字母字符的單詞
cursor = wordsColl.find({otherChars: {$exists: true}});
displayWords("Words with non-alphabet characters: ", cursor);

//查找這樣的文檔:子文檔數組字段charsets包含字段type爲other,數組字段chars長度爲2
cursor = wordsColl.find({charsets:{
                          $elemMatch:{
                            $and:[{type: 'other'},
                                  {chars: {$size: 1}}]}}});
displayWords("Words with 1 non-alphabet characters: ", cursor);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章