MongoDB中插入文档的几种方式是怎样的

Admin 2022-11-23 群英技术资讯 1455 次浏览

这篇主要是介绍“MongoDB中插入文档的几种方式是怎样的”的内容了,下文有实例供大家参考,对大家了解操作过程或相关知识有一定的帮助,而且实用性强,希望这篇文章能帮助大家解决MongoDB中插入文档的几种方式是怎样的的问题,下面我们一起来了解看看吧。

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

本文给大家介绍MongoDB的插入文档的方法,一起看看吧

1、文档的数据存储格式为BSON,类似于JSON。MongoDB插入数据时会检验数据中是否有“_id”,如果没有会自动生成。

shell操作有insert和save两种方法。当插入一条数据有“_id”值,并且现在集合中已经有相同的值,使用insert插入时插入不进去,使用save时,会更新数据。

> db.student.drop()
true
> db.student.insert({"_id": 1, "name":"zhangsan", "age": 28})
WriteResult({ "nInserted" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 28 }
> db.student.insert({"_id": 1, "name":"zhangsan", "age": 27})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: zyhdb.student index: _id_ dup key: { : 1.0 }"
}
})
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 28 }
> db.student.save({"_id": 1, "name":"zhangsan", "age": 27})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 27 } 

2、批量插入,网上的文档都说不能MongoDB不支持批量插入,现在试过可以,应该是目前的版本支持批量插入了。

> db.student.insert([{"_id": 2, "name": "lisi"},{"_id": 3, "name": "wangwu"}, {"_id": 4, "name": "zhaoliu", "age": 28}])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 27 }
{ "_id" : , "name" : "lisi" }
{ "_id" : , "name" : "wangwu" }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 } 

3、循环插入:

> for(var i=; i db.fortest.find()
{ "_id" : ObjectId("eceadaeabab"), "num" : 0}
{ "_id" : ObjectId("eceadaeabab"), "num" : 1}
{ "_id" : ObjectId("eceadaeabab"), "num" : 2}
{ "_id" : ObjectId("eceadaeabab"), "num" : 3}
{ "_id" : ObjectId("eceadaeabab"), "num" : 4}
{ "_id" : ObjectId("eceadaeababa"), "num" : 5}
{ "_id" : ObjectId("eceadaeababb"), "num" : 6}
{ "_id" : ObjectId("eceadaeababc"), "num" : 7}
{ "_id" : ObjectId("eceadaeababd"), "num" : 8}
{ "_id" : ObjectId("eceadaeababe"), "num" : 9}

到此,关于“MongoDB中插入文档的几种方式是怎样的”的学习就结束了,希望能够解决大家的疑惑,另外大家动手实践也很重要,对大家加深理解和学习很有帮助。如果想要学习更多的相关知识,欢迎关注群英网络,小编每天都会给大家分享实用的文章!

群英智防CDN,智能加速解决方案

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

猜你喜欢

成为群英会员,开启智能安全云计算之旅

立即注册
专业资深工程师驻守
7X24小时快速响应
一站式无忧技术支持
免费备案服务
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 或 0668-2555555
在线客服
微信公众号
返回顶部
返回顶部 返回顶部
在线客服
在线客服