首先我们先使用use指令创建数据库,在MongoDB中,use dbname,如果数据库不存在,则创建,并切换到使用该数据库,如果存在则直接切换到该数据库。其中,第一个db为别名,第二个db为数据库的名字。这个地方我的命名不太好。
其次,说明在shell中查询函数的方法:例如我们查询删除函数remove()的方法,我们可以使用如下的形式获取remove的实现形式:
> db.foo.remove
function (t, justOne) {
var parsed = this._parseRemove(t, justOne);
var query = parsed.query;
var justOne = parsed.justOne;
var wc = parsed.wc;
var collation = parsed.collation;
var result = undefined;
var startTime =
(typeof(_verboseShell) === 'undefined' || !_verboseShell) ? 0 : new Date().getTime();
if (this.getMongo().writeMode() != "legacy") {
var bulk = this.initializeOrderedBulkOp();
var removeOp = bulk.find(query);
if (collation) {
removeOp.collation(collation);
}
if (justOne) {
removeOp.removeOne();
} else {
removeOp.remove();
}
try {
result = bulk.execute(wc).toSingleResult();
} catch (ex) {
if (ex instanceof BulkWriteError || ex instanceof WriteCommandError) {
result = ex.toSingleResult();
} else {
// Other exceptions thrown
throw Error(ex);
}
}
} else {
if (collation) {
throw new Error("collation requires use of write commands");
}
this._validateRemoveDoc(t);
this.getMongo().remove(this._fullName, query, justOne);
// enforce write concern, if required
if (wc)
result = this.runCommand("getLastError", wc instanceof WriteConcern ? wc.toJSON() : wc);
}
this._printExtraInfo("Removed", startTime);
return result;
}
1、插入并保存文档:使用关键字insert()
> db.foo.insert({"daname":"db"})——执行该语句插入并保存文档
WriteResult({ "nInserted" : 1 })——返回插入结果
通过查询语句可以查询到该数据:
> db.foo.find()
{ "_id" : ObjectId("5a54c4936b41a70c4456a0cb"), "daname" : "db" }
2、批量插入:执行批量插入可以提高性能。可以使用mongoimport导入数据。
3、在执行插入操作时,驱动会将数据转换成BSON的形式,然后将其送入数据库。数据库在解析BSON时,检验是否包含"_id"键,并且文档不超过4M,除此之外,不做别的数据验证,就只是简单的将文档原样存入数据库中。——优点:远离注入式攻击,缺点:允许插入无效数据。
4、删除文档:db.foo.remove()
> db.foo.remove( )
2018-01-09T21:54:48.360+0800 E QUERY [thread1] Error: remove needs a query
直接使用时,会报错,需要添加删除条件:如下所示:
> db.foo.remove({"daname":"db"})——条件:{"键":"值","键":"值",……}
WriteResult({ "nRemoved" : 1 })——影响行数
如果想删除所有语法:
db.foo.remove({})
WriteResult({ "nRemoved" : 100 })
5、如果要删除集合:
> db.foo.drop()
true
6、如何模糊匹配删除将在后续blog中编写。
7、更新:使用update更新文档,有两个参数:一个是查询文档,用于获得需要修改的文档,另外一个是修改器。使用方法举例:
【文档替换的方式】
修改:
{ "_id" : ObjectId("5a5f71213d8be611a4cdd8e6"), "name" : "joe", "friends" : 32, "enemies" : 2 }
为:
{"_id" : ObjectId("5a5f71213d8be611a4cdd8e6"),"relationShips" : {"friends" : 32, "enemies" : 2},"username" : "joe"}
方法:
> var joe = db.foo.findOne({"name":"joe"}) ;
> joe.relationShips={"friends":joe.friends,"enemies":joe.enemies};
> joe.username = joe.name;
> delete joe.friends;
> delete joe.enemies;
> delete joe.name;
> db.foo.update({"name":"joe"},joe)
【注意】在更新时,最好查询条件使用_id,以保证唯一性,使用其他字段,可能获得到多个文,导致更新失败。
【使用修改器】用法将在一篇博客中讲解。