之前的笔记也提到了,我这里学习使用的是3.0.6版本的,与之前的版本有一定的差异,建议去官网学习教程,学习地址:MongoDB官网CRUD学习教程(ps:全英文),如果你觉得看不懂,那么我推荐你去看这个教程:易百的教程。
Insert( ) :
> db.collection.insert()
前面创建 collection 时也提到了,insert( ) 方法会自动创建不存在的 collection . 另外之前也提到了 MongoDB 的客户端也是一个 js 编译器,我们可以创建一个对象,然后插入。还有就是 MongoDB 的 collection 不会像表那样,insert( ) 插入的值没有限定 。
> var document = {
> "name" : "admin",
> "age" : 20,
> "address" : {
> "privonce" : "shanghai",
> "city" : "shanghai"
> },
> "group" : [ "news" , "sport" ]
> }
>
> db.user.insert( document )
WriteResult({ "nInserted" : 1 })
> document.name = "system"
system
> db.user.insert( document )
WriteResult({ "nInserted" : 1 })
图中也可以看到 MongoDB 会自动创建“_id”,它的类型是 ObjectId,较早的版本是不支持多条插入的,现在可以了
> var documents = [
> {
> "name" : "test1",
> "age" : 20,
> "address" : {
> "privonce" : "shanghai",
> "city" : "shanghai"
> },
> "group" : [ "news" , "sport" ]
> },{
> "name" : "test2",
> "age" : 20,
> "address" : {
> "privonce" : "shanghai",
> "city" : "shanghai"
> },
> "group" : [ "news" , "sport" ]
> }
> ];
> db.user.insert(document)
插入后返回一个对象的运行状态bulkwriteresult。一个成功的插入文件返回以下信息:
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
Bulk
Bulk 这种模式更像 MySql 的添加操作,个人觉得知道 insert( ) 就足够了,我这里就引用官网的例子。
/* 创建 bulk 对象 */
var bulk = db.inventory.initializeUnorderedBulkOp();
/* 添加插入数据 */
bulk.insert(
{
item: "BE10",
details: { model: "14Q2", manufacturer: "XYZ Company" },
stock: [ { size: "L", qty: 5 } ],
category: "clothing"
}
);
bulk.insert(
{
item: "ZYT1",
details: { model: "14Q1", manufacturer: "ABC Company" },
stock: [ { size: "S", qty: 5 }, { size: "M", qty: 5 } ],
category: "houseware"
}
);
/* 提交插入 */
bulk.execute();
/* 插入返回结果 */
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})