mongoDB shell中管理数据库和集合、在集合中查找文档

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LuuvyJune/article/details/89230258

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);

猜你喜欢

转载自blog.csdn.net/LuuvyJune/article/details/89230258