Home >Database >Mysql Tutorial >MongoDB操作手册CRUD插入

MongoDB操作手册CRUD插入

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-07 16:05:111177browse

插入操作 插入记录 1.插入一条记录 db.testData.insert({num:1,name:'a'}); 结果 WriteResult({ nInserted : 1 }) 2.查看插入的记录 db.testData.find(); 插入数组 1.定义数组 var arr = [{num:1,name:'a'},{num:2,name:'b'},{num:3,name:'c'}]; 2.插入记录

插入操作

插入记录

1.插入一条记录 db.testData.insert({num:1,name:'a'}); 结果 WriteResult({ "nInserted" : 1 })
2.查看插入的记录 db.testData.find();

插入数组

1.定义数组 var arr = [{num:1,name:'a'},{num:2,name:'b'},{num:3,name:'c'}];
2.插入记录 db.testData.insert(arr);
结果 nInserted显示插入了几条数据
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})

批量插入多条数据

bulk是2.6的新特性
1.初始化指定集合的批处理操作构造器 var bulk = db.testData.initializeUnorderedBulkOp(); //初始化未排序的批处理操作
这个操作返回一个维护着操作列表的未排序操作构造器。未排序的意思是MongoDB可以同步执行没有顺序的多个操作。
如果期间发生错误,将继续执行后续操作。
也可以构建一个有序的操作构造器,查看db.collection.initializeOrderedBulkOp();
2.将插入操作添加进bulk对象中
bulk.insert({num:4,name:'d'});
bulk.insert({num:5,name:'e'});
3.执行批处理
bulk.execute();
返回批处理的结果,nInserted表示插入几条,如果期间发生错误,将包含在结果中。
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})

额外的例子和方法

db.collection.update() method,
db.collection.findAndModify(),
db.collection.save()
这几个方法也可以执行插入操作。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:用户Next article:自考颗粒归仓-----数据库原理概况