MongoDB的一些基本操作

406 阅读2分钟

MongoDB的基本概念

MongoDB以BSON格式的文档(Documents)形式存储。Databases中包含集合(Collections),集合(Collections)中存储文档(Documents)。BSON是一个二进制形式的JSON文档,它比JSON包含更多的数据类型。

在MongoDB中,databases保存文档(Documents)的集合(Collections),Collections类似于关系型数据库中的表(tables)。

新建数据库

use customers

use命令可以用来切换db或者生成新db

第一次生成db时,因为没有collections,所以show dbs不会显示

> db.createCollection("hello");
{ "ok" : 1 }
> show dbs;
admin      0.000GB
config     0.000GB
customers  0.000GB
local      0.000GB

删除数据库

> db.dropDatabase();

查询MongoDB的命令

> db.help();
DB methods:
	db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]
	db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor
	db.auth(username, password)
	db.commandHelp(name) returns the help for the command
	db.createUser(userDocument)
	db.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions})
	db.currentOp() displays currently executing operations in the db
	db.dropDatabase(writeConcern)
	db.dropUser(username)
	db.eval() - deprecated
	db.fsyncLock() flush data to disk and lock server for backups
	db.fsyncUnlock() unlocks server following a db.fsyncLock()
	db.getCollection(cname) same as db['cname'] or db.cname
	db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
	db.getCollectionNames()
	db.getLastError() - just returns the err msg string
	db.getLastErrorObj() - return full status object
	db.getLogComponents()
	db.getMongo() get the server connection object
	db.getMongo().setSecondaryOk() allow queries on a replication secondary server
	db.getName()
	db.getProfilingLevel() - deprecated
	db.getProfilingStatus() - returns if profiling is on and slow threshold
	db.getReplicationInfo()
	db.getSiblingDB(name) get the db at the same server as this one
	db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
	db.hostInfo() get details about the server's host
	db.isMaster() check replica primary status
	db.hello() check replica primary status
	db.killOp(opid) kills the current operation in the db
	db.listCommands() lists all the db commands
	db.loadServerScripts() loads all the scripts in db.system.js
	db.logout()
	db.printCollectionStats()
	db.printReplicationInfo()
	db.printShardingStatus()
	db.printSecondaryReplicationInfo()
	db.rotateCertificates(message) - rotates certificates, CRLs, and CA files and logs an optional message
	db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into {cmdObj: 1}
	db.serverStatus()
	db.setLogLevel(level,<component>)
	db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
	db.setVerboseShell(flag) display extra information in shell output
	db.setWriteConcern(<write concern doc>) - sets the write concern for writes to the db
	db.shutdownServer()
	db.stats()
	db.unsetWriteConcern(<write concern doc>) - unsets the write concern for writes to the db
	db.version() current version of the server
	db.watch() - opens a change stream cursor for a database to report on all  changes to its non-system collections.

Collections的基本操作

MongoDB 可以显式创建一个collections,也可以直接向一个不存在的collections插入数据时,自动创建一个collections。

显式创建,可以指定collections的参数。

> db.createCollection("person", { capped: true, size: 6142800, max: 3000})
{ "ok" : 1 }
> show collections;
hello
person
> db.person.stats()

删除collections

> db.person.drop();
true

隐式创建一个collections.

> db.person.insert({x:1});
WriteResult({ "nInserted" : 1 })
> show collections;
hello
person
> 

documents的基本操作

将以下的student json object粘贴在MongoDB Shell中,回车

student = {
	"firstName": "Michael",
	"lastName": "Steinert",
	"email": "mSteinert@mysql.com",
	"gender": "M",
	"country": "Australia",
	"isStudentActive": true,
	"favouriteSubjects" : [
		"maths",
		"english",
		"it"
	],
	"totalSpentInBooks": 0.00
}

然后输入 db.student.insert(student),第一个student是colletion,第二个是student json object。

> student = {
... "firstName": "Michael",
... "lastName": "Steinert",
... "email": "mSteinert@mysql.com",
... "gender": "M",
... "country": "Australia",
... "isStudentActive": true,
... "favouriteSubjects" : [
... "maths",
... "english",
... "it"
... ],
... "totalSpentInBooks": 0.00
... }
{
	"firstName" : "Michael",
	"lastName" : "Steinert",
	"email" : "mSteinert@mysql.com",
	"gender" : "M",
	"country" : "Australia",
	"isStudentActive" : true,
	"favouriteSubjects" : [
		"maths",
		"english",
		"it"
	],
	"totalSpentInBooks" : 0
}
> db.student.insert(student)
WriteResult({ "nInserted" : 1 })

插入多条json object

students = [
	{
		"firstName": "Cally",
		"lastName": "Walkden",
		"email": "Cally@mysql.com",
		"gender": "M",
		"country": "China",
		"isStudentActive": false,
		"favouriteSubjects" : [
			"maths",
			"english"
		],
		"totalSpentInBooks": 42.00
	},
	{
		"firstName": "Marie",
		"lastName": "Schmidt",
		"email": "Marie@gmail.com",
		"gender": "F",
		"country": "Niger",
		"isStudentActive": true,
		"favouriteSubjects" : [
			"it",
			"chemist"
		],
		"totalSpentInBooks": 165.00
	}
]

粘贴,回车,执行

> db.student.insertMany(students);
{
	"acknowledged" : true,
	"insertedIds" : [
		ObjectId("616769c06a02c016d60cca39"),
		ObjectId("616769c06a02c016d60cca3a")
	]
}
> db.student.count()
3

MongoDB的查询

一些简单查询

> db.student.count()
1
> db.student.find().pretty()
{
	"_id" : ObjectId("6167661f6a02c016d60cca38"),
	"firstName" : "Michael",
	"lastName" : "Steinert",
	"email" : "mSteinert@mysql.com",
	"gender" : "M",
	"country" : "Australia",
	"isStudentActive" : true,
	"favouriteSubjects" : [
		"maths",
		"english",
		"it"
	],
	"totalSpentInBooks" : 0
}

按条件查询 image.png 1, query criteria的取值 image.png 2,projection的取值:

  • 1或true在 return 文档中包含该字段。
  • 0或false排除该字段。
  • 表达式使用投影操作员。
> db.student.find({firstName:'Cally'}).pretty()
{
	"_id" : ObjectId("616769c06a02c016d60cca39"),
	"firstName" : "Cally",
	"lastName" : "Walkden",
	"email" : "Cally@mysql.com",
	"gender" : "M",
	"country" : "China",
	"isStudentActive" : false,
	"favouriteSubjects" : [
		"maths",
		"english"
	],
	"totalSpentInBooks" : 42
}
> db.student.find({firstName:'Cally'},{firstName:1,lastName:true,gender:1}).pretty()
{
	"_id" : ObjectId("616769c06a02c016d60cca39"),
	"firstName" : "Cally",
	"lastName" : "Walkden",
	"gender" : "M"
}
> db.student.find({$or:[{firstName:'Cally'},{firstName:'Marie'}]},{firstName:1,lastName:true,gender:1}).pretty()
{
	"_id" : ObjectId("616769c06a02c016d60cca39"),
	"firstName" : "Cally",
	"lastName" : "Walkden",
	"gender" : "M"
}
{
	"_id" : ObjectId("616769c06a02c016d60cca3a"),
	"firstName" : "Marie",
	"lastName" : "Schmidt",
	"gender" : "F"
}
> 

MongoDB更新数据-update

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)
  • query : update的查询条件,类似sql update查询内where后面的。
  • update : update的对象和一些更新的操作符(如,,inc...)等,也可以理解为sql update查询内set后面的
  • upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
  • multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。

例子:

> db.student.update({_id: ObjectId("616769c06a02c016d60cca39")}, {$set: {firstName:'Calley'},$inc: {totalSpentInBooks: 10}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

类似于SQL语法中的

update student set firstName='Calley',totalSpentInBooks=totalSpentInBooks+10 where _id="616769c06a02c016d60cca39"

MongoDB删除数据-delete

删除一条记录

db.collection.deleteOne(
    <filter>,
    {
        writeConcern: <document>,
        collation: <document>
    }
)

删除多条记录

db.collection.deleteMany(
    <filter>,
    {
        writeConcern: <document>,
        collation: <document>
    }
)

例子:

> db.student.deleteOne({_id: ObjectId("616769c06a02c016d60cca39")})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.student.deleteMany({gender: 'M'})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.student.find()
{ "_id" : ObjectId("616769c06a02c016d60cca3a"), "firstName" : "Marie", "lastName" : "Schmidt", "email" : "Marie@gmail.com", "gender" : "F", "country" : "Niger", "isStudentActive" : true, "favouriteSubjects" : [ "it", "chemist" ], "totalSpentInBooks" : 165 }