mongodb插入数据_MongoDB插入
mongodb插入数据
Today we will look into MongoDB insert commands. Mongo Client can be used to insert a document into a collection. We can also insert an array of documents, today we will look into various operations related to MongoDB insert.
今天,我们将研究MongoDB插入命令。 Mongo Client可用于将文档插入集合中。 我们还可以插入一系列文档,今天我们将研究与MongoDB insert相关的各种操作。
MongoDB插入 (MongoDB insert)
For MongoDB insert example, I am using MongoDB version 3.4.7 and java driver version 3.5.0. However these should work with other versions too. Note that mongo java driver API has totally changed in 3.x version, so if you are using older 2.x version then you will have to modify the code accordingly.
对于MongoDB插入示例,我使用的是MongoDB版本3.4.7和Java驱动程序版本3.5.0。 但是,这些也应与其他版本一起使用。 请注意,mongo Java驱动程序API在3.x版本中已完全更改,因此,如果您使用的是旧版2.x版本,则必须相应地修改代码。
使用Mongo Client插入MongoDB (MongoDB insert using Mongo Client)
Here is a simple example where I am inserting a single document into Person collection.
这是一个简单的示例,其中我将一个文档插入Person集合。
pankaj:mongodb pankaj$ mongo
MongoDB shell version v3.4.7
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.7
Welcome to the MongoDB shell.
For interactive help, type "help".
> use journaldev
switched to db journaldev
> show collections
> db.Persons.insert({name:"Pankaj",country:"India"})
WriteResult({ "nInserted" : 1 })
> show collections
Persons
> db.Persons.find()
{ "_id" : ObjectId("59a3d6bf03ca62436260d57a"), "name" : "Pankaj", "country" : "India" }
>
Notice that if we don’t provide primary key i.e _id
key, MongoDB automatically generates it and it gets stored as ObjectId
object.
请注意,如果我们不提供主键(即_id
键),MongoDB会自动生成它并将其存储为ObjectId
对象。
Also check that it’s returning WriteResult
object containing the number of documents inserted. If the collection doesn’t exists, MongoDB will create it.
还要检查它是否返回包含插入的文档数的WriteResult
对象。 如果该集合不存在,MongoDB将创建它。
用主键插入MongoDB (MongoDB insert with primary key)
Now let’s provide primary key to the mongodb document and see different scenarios that can occur.
现在,让我们提供mongodb文档的主键,并查看可能发生的不同情况。
MongoDB insert single document with id
MongoDB插入具有ID的单个文档
> db.Persons.insert({_id:123,name:"Pankaj",country:"India"})
WriteResult({ "nInserted" : 1 })
> db.Persons.find()
{ "_id" : ObjectId("53fc3dc9b1e38e3716f79113"), "name" : "Pankaj", "country" : "India" }
{ "_id" : 123, "name" : "Pankaj", "country" : "India" }
>
What if there is already an object stored with the provided id.
如果已经存储了提供的ID的对象该怎么办。
MongoDB insert document duplicate key error
MongoDB插入文档重复键错误
> db.Persons.insert({_id:123,name:"David",country:"India"})
WriteResult({"nInserted" : 0,"writeError" : {"code" : 11000,"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: journaldev.Persons.$_id_ dup key: { : 123.0 }"}
})
>
Well, from the output it seems that WriteResult also provide error code and message associated with it, notice that rows inserted is returned as 0.
好了,从输出看来,WriteResult还提供了错误代码和与之相关的消息,请注意,插入的行返回为0。
MongoDB批量插入 (MongoDB bulk insert)
Now let’s try the insert multiple documents with a single command.
现在,让我们尝试使用一个命令插入多个文档。
> db.Persons.insert([{name:"David"},{name:"Kumar"}])
BulkWriteResult({"writeErrors" : [ ],"writeConcernErrors" : [ ],"nInserted" : 2,"nUpserted" : 0,"nMatched" : 0,"nModified" : 0,"nRemoved" : 0,"upserted" : [ ]
})
>
So with an array of documents, MongoDB insert operation returns BulkWriteResult
that contains more information.
因此,对于一系列文档,MongoDB插入操作将返回包含更多信息的BulkWriteResult
。
Let’s try to insert array of documents with id also.
让我们尝试插入具有ID的文档数组。
> db.Persons.insert([{_id:100,name:"David"},{_id:101,name:"Kumar"}])
BulkWriteResult({"writeErrors" : [ ],"writeConcernErrors" : [ ],"nInserted" : 2,"nUpserted" : 0,"nMatched" : 0,"nModified" : 0,"nRemoved" : 0,"upserted" : [ ]
})
>
Now let’s see what happens when there is an error in inserting one of the documents in the array.
现在,让我们看看在数组中插入一个文档时出错。
> db.Persons.insert(
... [{_id:102,name:"PK"},
... {_id:101,name:"Kumar"},
... {_id:103,name:"PK"}])
BulkWriteResult({"writeErrors" : [{"index" : 1,"code" : 11000,"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: journaldev.Persons.$_id_ dup key: { : 101.0 }","op" : {"_id" : 101,"name" : "Kumar"}}],"writeConcernErrors" : [ ],"nInserted" : 1,"nUpserted" : 0,"nMatched" : 0,"nModified" : 0,"nRemoved" : 0,"upserted" : [ ]
})
> db.Persons.find()
{ "_id" : ObjectId("53fc3dc9b1e38e3716f79113"), "name" : "Pankaj", "country" : "India" }
{ "_id" : 123, "name" : "Pankaj", "country" : "India" }
{ "_id" : ObjectId("53fc40d1b1e38e3716f79114"), "name" : "David" }
{ "_id" : ObjectId("53fc40d1b1e38e3716f79115"), "name" : "Kumar" }
{ "_id" : 100, "name" : "David" }
{ "_id" : 101, "name" : "Kumar" }
{ "_id" : 102, "name" : "PK" }
>
It’s clear that operation is terminated when any of the document insertion fails, any further records are not inserted and we get error message clearly showing which of the record caused the issue.
很显然,当任何文档插入失败,没有再插入任何其他记录时,操作就会终止,并且我们会收到错误消息,清楚地表明哪个记录引起了问题。
MongoDB大容量插入排序和writeConcern参数 (MongoDB bulk insert ordered and writeConcern parameters)
What if we are executing a bulk operation and want to process error documents later on, we can use ordered
parameter to tell MongoDB to skip the error document.
如果我们要执行批量操作并希望稍后处理错误文档,可以使用ordered
参数告诉MongoDB跳过错误文档该怎么办。
> db.Persons.insert( [{_id:102,name:"PK"}, {_id:101,name:"Kumar"}, {_id:103,name:"PK"}] ,{ordered:false})
BulkWriteResult({"writeErrors" : [{"index" : 0,"code" : 11000,"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: journaldev.Persons.$_id_ dup key: { : 102.0 }","op" : {"_id" : 102,"name" : "PK"}},{"index" : 1,"code" : 11000,"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: journaldev.Persons.$_id_ dup key: { : 101.0 }","op" : {"_id" : 101,"name" : "Kumar"}}],"writeConcernErrors" : [ ],"nInserted" : 1,"nUpserted" : 0,"nMatched" : 0,"nModified" : 0,"nRemoved" : 0,"upserted" : [ ]
})
> db.Persons.find()
{ "_id" : ObjectId("53fc3dc9b1e38e3716f79113"), "name" : "Pankaj", "country" : "India" }
{ "_id" : 123, "name" : "Pankaj", "country" : "India" }
{ "_id" : ObjectId("53fc40d1b1e38e3716f79114"), "name" : "David" }
{ "_id" : ObjectId("53fc40d1b1e38e3716f79115"), "name" : "Kumar" }
{ "_id" : 100, "name" : "David" }
{ "_id" : 101, "name" : "Kumar" }
{ "_id" : 102, "name" : "PK" }
{ "_id" : 103, "name" : "PK" }
>
Similarly we can also pass writeConcern
parameter for different levels of concerns, default write concern is Acknowledged. We will look into it in future post.
同样,我们也可以为不同级别的关注点传递writeConcern
参数,默认的写关注点被确认。 我们将在以后的文章中对此进行研究。
MongoDB插入Java示例 (MongoDB insert Java Example)
Now let’s see different ways to use Java Driver to perform insert operations in MongoDB collection. Note that these java programs are using mongo-java-driver
version 3.5.0
.
现在,让我们看看使用Java驱动程序在MongoDB集合中执行插入操作的不同方法。 请注意,这些Java程序使用的是mongo-java-driver
版本3.5.0
。
MongoDB插入单个文档的示例 (MongoDB insert single document example)
A simple program inserting a single document using
MongoCollection.insertOne
method.一个简单的程序,使用
MongoCollection.insertOne
方法插入单个文档。package com.journaldev.mongodb.main;import java.net.UnknownHostException;import org.bson.Document;import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase;public class MongoDBInsertExample {public static void main(String[] args) throws UnknownHostException {MongoClient mongo = new MongoClient("localhost", 27017);MongoDatabase db = mongo.getDatabase("journaldev");MongoCollection<Document> col = db.getCollection("Persons");Document document = new Document();document.append("name", "Pankaj");document.append("country", "USA");col.insertOne(document);System.out.println("ID Generated=" + document.getObjectId("_id").toString());mongo.close();}}
Below image shows the output produced, notice the generated id being printed to console.
下图显示了生成的输出,请注意生成的ID正在打印到控制台。
We can also pass our own id parameter like below.
我们还可以像下面这样传递我们自己的id参数。
document.append("_id",new ObjectId("123456789012".getBytes())); //min byte array length should be 12 document.append("_id", new ObjectId(new Date())); // ObjectId constructor also takes Date as argument
However if we are trying to create instance of ObjectId by passing some parameter, such as
document.append("_id",new ObjectId("1234"));
, it will throw below exception.但是,如果我们尝试通过传递一些参数来创建ObjectId的实例,例如
document.append("_id",new ObjectId("1234"));
,它将抛出异常。Exception in thread "main" java.lang.IllegalArgumentException: invalid hexadecimal representation of an ObjectId: [1234]at org.bson.types.ObjectId.parseHexString(ObjectId.java:549)at org.bson.types.ObjectId.<init>(ObjectId.java:239)at com.journaldev.mongodb.main.MongoDBInsertExample.main(MongoDBInsertExample.java:24)
It’s because some validations are in place when argument is passed for ObjectId, the passed String should be a hexadecimal string. You can check it’s source code for more details.
这是因为在为ObjectId传递参数时已经进行了一些验证,传递的String应该是十六进制字符串。 您可以查看其源代码以获取更多详细信息。
If you try to pass ObjectId like
document.append("_id", new ObjectId("1234".getBytes()));
, it will throw following exception.如果您尝试传递诸如
document.append("_id", new ObjectId("1234".getBytes()));
,它将引发以下异常。Exception in thread "main" java.lang.IllegalArgumentException: state should be: buffer.remaining() >=12at org.bson.assertions.Assertions.isTrueArgument(Assertions.java:62)at org.bson.types.ObjectId.<init>(ObjectId.java:272)at org.bson.types.ObjectId.<init>(ObjectId.java:249)at com.journaldev.mongodb.main.MongoDBInsertExample.main(MongoDBInsertExample.java:33)
The reason is that byte array minimum size should be 12.
原因是字节数组的最小大小应为12。
MongoDB插入Map Java程序 (MongoDB insert Map java program)
If you look at
Document
example above, you will find it’s very similar to Map. We can insert a Map easily as a document, sample code snippet is given below.如果您看一下上面的
Document
示例,您会发现它与Map非常相似。 我们可以轻松地将Map插入为文档,示例代码段如下所示。Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap.put("name", "Pankaj"); dataMap.put("country", "USA"); dataMap.put("_id",new ObjectId("123459789012".getBytes()));Document document = new Document(dataMap);col.insertOne(document);
MongoDB插入JSON文档 (MongoDB insert JSON Document)
Sometimes we get JSON response, mostly when we are invoking web services. That’s why MongoDB provides an easy way to insert JSON document in MongoDB collection, as shown in below example.
有时我们会得到JSON响应,主要是在调用Web服务时。 这就是为什么MongoDB提供了一种在MongoDB集合中插入JSON文档的简单方法,如下面的示例所示。
String json = "{ 'name' : 'Pankaj', 'country' : 'USA' }"; Document document = Document.parse(json);col.insertOne(document);
插入多个文件 (Inserting multiple documents)
We can insert multiple documents too using Mongo java driver, a simple example is shown below.
我们也可以使用Mongo Java驱动程序插入多个文档,下面显示一个简单的示例。
package com.journaldev.mongodb.main;import java.util.ArrayList; import java.util.List;import org.bson.Document;import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase;public class MongoDBInsertMultipleExample {public static void main(String[] args) {MongoClient mongo = new MongoClient("localhost", 27017);MongoDatabase db = mongo.getDatabase("journaldev");MongoCollection<Document> col = db.getCollection("Persons");List<Document> docs = new ArrayList<>();docs.add(new Document("name", "Pankaj"));docs.add(new Document().append("name", "David"));col.insertMany(docs);for(Document doc : docs) {System.out.println("Name="+doc.getString("name")+", ID="+doc.getObjectId("_id").toString());}mongo.close();}}
Output produced will be something like below.
产生的输出将如下所示。
Name=Pankaj, ID=59a404c9c5130d39760a01a2 Name=David, ID=59a404c9c5130d39760a01a3
That’s all for MongoDB insert example, we will look into more MongoDB features in coming posts.
这就是MongoDB插入示例的全部内容,我们将在以后的文章中研究更多MongoDB功能。
翻译自: https://www.journaldev.com/4308/mongodb-insert
mongodb插入数据
mongodb插入数据_MongoDB插入相关推荐
- java mongodb 插入数据_mongoDB 插入数据 用java实现
import java.net.UnknownHostException; import com.mongodb.BasicDBObject; import com.mongodb.DB; impor ...
- mysql设置id为主键且设置自增长时插入数据无法插入解决
当你遇到这个问题的时候你可能会有以下几个解决方案 1.插入数据时将id值设为"null"或者是" " 如:insert into biao1 values('' ...
- json 插入数据_MongoDB如何一次插入多条json数据
背景 MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是 ...
- influxdb 插入数据_influxdb 插入数据遇到的坑
partial write: max-values-per-tag limit exceeded 这个问题可能会出现较早的版本,有些版本限定了tag的数目,不能超过10w.过多tag会导致的问题在前面 ...
- MyBatis插入数据返回插入对象的主键
1.美图 方法:在mapper中指定keyProperty属性,示例如下: 主要: useGeneratedKeys="true" keyProperty="userId ...
- 完美解决SSM中 java.lang...c3p0/impl/NewProxyResultSet.isClosed()Z is abstract 【插入数据只能插入一条问题】
报错信息如下 解决办法 在pom.xml文件中修改我们引入的c3p0依赖的jar包: 之前是: <!--数据库连接池 驱动--><!-- https://mvnrepository. ...
- php创建表并插入数据,php数据库操作-创建库和表以及插入数据
以上我们正确连接到了mysql数据库,本文将进一步创建数据库,表,在表中填充数据. 大家知道连接上数据库才能进行操作,同样的代码搬过来 /* * 数据库操作*(创建数据库,表,插入数据,插入多条数据) ...
- 【原】.Net创建Excel文件(插入数据、修改格式、生成图表)的方法
1.添加Excel引用 可以在.Net选项卡下添加Microsoft.Office.Interop.Excel引用,或在COM下添加Microsoft Excel 12.0 Object Librar ...
- SQL点滴系列之插入数据(四)
[SQL从一点一滴分析系列文章]为实际开发中的点点滴滴的总结,从最最简单的SQL 查询 到 综合分析查询 在分析 SQL 时,也会同时分析 mybatis .Hibernate 中的相关操作 点击查看 ...
最新文章
- 哪个才是解决回归问题的最佳算法?线性回归、神经网络还是随机森林?
- Kubernetes是什么
- 我的.gitignore下配置。存在这里一下。日后有空研究研究!
- 特岗计算机老师年度总结,特岗教师个人年度工作总结
- php mysqli::close()
- Nat. Biotechnol. | 利用深度学习从基因转录数据中预测药物疗效
- 神奇的文本编辑,惊人的移花接木 | ACM MM 2019 论文赏析
- 博客迁移到github
- linux 备份iphone,用linux搭建Mac备份服务器,伪TimeCapsule
- MacBook 摄像头不工作怎么解决
- linux 解压加密zip,linux 系统下 zip 的加密压缩与解压缩命令
- OpenCV2:Mat属性type,depth,step
- 【visio】visio软件安装
- 2019三星比2018好在哪_【三星w2019和w2018参数对比资讯】三星w2019和w2018参数对比足球知识与常识 - 足球百科 - 599比分...
- rust键位失灵_switch手柄按键失灵不响应怎么办 NS手柄按键没反应解决办法
- 02尚硅谷书城案例-用户的注册
- Matplotlib的中文字体显示为方块的问题
- 1-3 Burpsuite 抓取手机APP流量
- 手游代理路上容易遇到哪些坑
- 贪玩蓝月服务器维护需多少时间,贪玩蓝月一般多久合区 | 手游网游页游攻略大全...