Ruby 操作 MongoDB(8)

2021-10-19 11:55:09 浏览数 (1)

创建数据库

即便一个库不存在,如果往这个库里插入数据,就会连同集合一起,自动被创建

上面的操作过程中已经将 post 数据库删除了,于是我执行下面的语句

代码语言:javascript复制
2.3.0 :051 > db1[:abctest].insert_one({name: 'justfortest'})
D, [2016-05-26T22:58:31.161257 #32905] DEBUG -- : MONGODB | 192.168.100.105:27017 | post.insert | STARTED | {"insert"=>"abctest", "documents"=>[{:name=>"justfortest", :_id=>BSON::ObjectId('57470f17f677048089c7f028')}], "ordered"=>true}
D, [2016-05-26T22:58:31.197713 #32905] DEBUG -- : MONGODB | 192.168.100.105:27017 | post.insert | SUCCEEDED | 0.036217863s
 => #<Mongo::Operation::Result:11204100 documents=[{"ok"=>1, "n"=>1}]> 
2.3.0 :052 > db1.collection_names
D, [2016-05-26T22:58:42.023711 #32905] DEBUG -- : MONGODB | 192.168.100.105:27017 | post.listCollections | STARTED | {"listCollections"=>1, "cursor"=>{}, "filter"=>{:name=>{"$not"=>/system.|$/}}}
D, [2016-05-26T22:58:42.060270 #32905] DEBUG -- : MONGODB | 192.168.100.105:27017 | post.listCollections | SUCCEEDED | 0.036180602s
 => ["abctest"] 
2.3.0 :053 > db1[:abctest].find().to_a
D, [2016-05-26T23:03:22.076758 #32905] DEBUG -- : MONGODB | 192.168.100.105:27017 | post.find | STARTED | {"find"=>"abctest", "filter"=>{}}
D, [2016-05-26T23:03:22.079052 #32905] DEBUG -- : MONGODB | 192.168.100.105:27017 | post.find | SUCCEEDED | 0.002194069s
 => [{"_id"=>BSON::ObjectId('57470f17f677048089c7f028'), "name"=>"justfortest"}] 
2.3.0 :054 >

本地查看一下

代码语言:javascript复制
> show dbs
local  0.000GB
post   0.000GB
> use post
switched to db post
> show tables
abctest
> db.abctest.find()
{ "_id" : ObjectId("57470f17f677048089c7f028"), "name" : "justfortest" }
> 

看来 post 库和 abctest 表外加 “name” : “justfortest” 的记录一同被创建了


索引操作

创建索引

MongoDB 3.0.0 之后的版本可以并行创建索引,之前的版本只能顺序创建

Indexes can be created one at a time, or multiples can be created in a single operation. When creating multiples on MongoDB 3.0.0 and higher, the indexes will be created in parallel, otherwise they will be created in order.

创建单个索引
代码语言:javascript复制
2.3.0 :054 > db1[:abctest].indexes.create_one({ :name => 1 }, :unique => true)
D, [2016-05-26T23:11:11.304095 #32905] DEBUG -- : MONGODB | 192.168.100.105:27017 | post.createIndexes | STARTED | {"reateIndexes"=>"abctest", "indexes"=>[{:key=>{:name=>1}, :unique=>true, :name=>"name_1"}]}
D, [2016-05-26T23:11:11.371189 #32905] DEBUG -- : MONGODB | 192.168.100.105:27017 | post.createIndexes | SUCCEEDED | .066713294s
 => #<Mongo::Operation::Result:5602320 documents=[{"createdCollectionAutomatically"=>false, "numIndexesBefore"=>1, "nmIndexesAfter"=>2, "ok"=>1.0}]> 
2.3.0 :055 >

看本地

代码语言:javascript复制
> db.abctest.getIndexes()
[
	{
		"v" : 1,
		"key" : {
			"_id" : 1
		},
		"name" : "_id_",
		"ns" : "post.abctest"
	},
	{
		"v" : 1,
		"unique" : true,
		"key" : {
			"name" : 1
		},
		"name" : "name_1",
		"ns" : "post.abctest"
	}
]
> 

0 人点赞