Note
MongoDB will add the _id field and assign a unique ObjectId for the document before inserting. Most drivers create an ObjectId and insert. MongoDB Bulk insert, mongodb insertMany, MongoDB insert multiple documents, mongodb batch insert, mongodb insert document, MongoDB bulk insert java program.
The following code snippets come from the
QuickTour.java
example codethat can be found with the driver source on github.Prerequisites
- A running MongoDB on localhost using the default port for MongoDB
27017
- MongoDB Driver. See Installation for instructions on how to install the MongoDB driver.
- The following import statements:
Make a Connection
Use
MongoClient()
to make a connection to a running MongoDB instance.The
MongoClient
instance represents a pool of connections to the database; you will only need one instance of class MongoClient
even with multiple threads.important
Typically you only create one
MongoClient
instance for a given MongoDB deployment (e.g. standalone, replica set, or a sharded cluster) and use it across your application. However, if you do create multiple instances:- All resource usage limits (e.g. max connections, etc.) apply per
MongoClient
instance. - To dispose of an instance, call
MongoClient.close()
to clean up resources.
Connect to a Single MongoDB instance
The following example shows five ways to connect to thedatabase
mydb
on the local machine. If the database does not exist, MongoDBwill create it for you.To connect to a single MongoDB instance:
- You can instantiate a MongoClient object without any parameters to connect to a MongoDB instance running on localhost on port
27017
:
- You can explicitly specify the hostname to connect to a MongoDB instance running on the specified host on port
27017
:
- You can explicitly specify the hostname and the port:
- You can specify the
MongoClientURI
connection string:
The connection string mostly follows RFC 3986, with the exception of the domain name. For MongoDB, it is possible to list multiple domain names separated by a comma. For more information on the connection string, see connection string.
Access a Database
Once you have a
MongoClient
instance connected to a MongoDB deployment, use the MongoClient.getDatabase()
method to access a database.Specify the name of the database to the
getDatabase()
method. If a database does not exist, MongoDB creates the database when you first store data for that database.The following example accesses the
mydb
database:MongoDatabase
instances are immutable.Access a Collection
Once you have a
MongoDatabase
instance, use its getCollection()
method to access a collection.Specify the name of the collection to the
getCollection()
method. If a collection does not exist, MongoDB creates the collection when you first store data for that collection.For example, using the
database
instance, the following statement accesses the collection named test
in the mydb
database:MongoCollection
instances are immutable.Create a Document
To create the document using the Java driver, use the
Document
class.For example, consider the following JSON document:
To create the document using the Java driver, instantiate a
Document
object with a field and value, and use its append()
method to include additional fields and values to the document object. The value can be another Document
object to specify an embedded document:Note
The BSON type of array corresponds to the Java type
java.util.List
. For a list of the BSON type and the corresponding type in Java, see .Insert a Document
Once you have the
MongoCollection
object, you can insert documents into thecollection.Insert One Document
To insert a single document into the collection, you can use the collection’s
insertOne()
method.Note
If no top-level
_id
field is specified in the document, MongoDB automatically adds the _id
field to the inserted document.Insert Multiple Documents
To add multiple documents, you can use the collection’s
insertMany()
method method which takes a list of documents to insert.The following example will add multiple documents of the form:
Create the documents in a loop and add to the
documents
list:To insert these documents to the collection, pass the list of documents to the
insertMany()
method.Note
If no top-level
_id
field is specified in the document, MongoDB automatically adds the _id
field to the inserted document.Count Documents in A Collection
To count the number of documents in a collection, you can use the collection’s
count()
method. The following code should print 101
(the 100 inserted via insertMany
plus the 1 inserted via the insertOne
).Query the Collection
To query the collection, you can use the collection’s
find()
method. You can call the method without any arguments to query all documents in a collection or pass a filter to query for documents that match the filter criteria.The
find()
method returns a FindIterable()
instance that provides a fluent interface for chaining other methods.Find the First Document in a Collection
To return the first document in the collection, use the
find()
method without any parameters and chain to find()
method the first()
method.If the collection is empty, the operation returns null.
tip
The
find().first()
construct is useful for queries that should only match a single document or if you are interested in the first document only.The following example prints the first document found in the collection.
The example should print the following document:
Note
The
_id
element has been added automatically by MongoDB to yourdocument and your value will differ from that shown. MongoDB reserves fieldnames that start with'_'
and '$'
for internal use.Find All Documents in a Collection
To retrieve all the documents in the collection, we will use the
find()
method without any parameters.To iterate through the results, chain the
iterator()
method to the find()
.The following example retrieves all documents in the collectionand prints the returned documents (101 documents):
Although the following idiom for iteration is permissible, avoid its use as the application can leak a cursor if the loop terminates early:
Specify a Query Filter
To to query for documents that match certain conditions, pass a filter object to the
find()
method. To facilitate creating filter objects, Java driver provides the Filters
helper.Get A Single Document That Matches a Filter
For example, to find the first document where the field
i
has the value 71
, pass an eq
filter object to specify the equality condition:The example prints one document:
Get All Documents That Match a Filter
The following example returns and prints all documents where
'i' > 50
:The example uses the }}'>
forEach
method on the FindIterable
object to apply a block to each document.To specify a filter for a range, such as
50 < i <= 100
, you can use the and
helper:Update Documents
To update documents in a collection, you can use the collection’s
updateOne
and updateMany
methods.Pass to the methods:
- A filter object to determine the document or documents to update. To facilitate creating filter objects, Java driver provides the
Filters
helper. To specify an empty filter (i.e. match all documents in a collection), use an emptyDocument
object. - An update document that specifies the modifications. For a list of the available operators, see update operators.
The update methods return an
UpdateResult
which provides information about the operation including the number of documents modified by the update.Update a Single Document
To update at most a single document, use the
updateOne
The following example updates the first document that meets the filter
i
equals 10
and sets the value of i
to 110
:Update Multiple Documents
To update all documents matching the filter, use the
updateMany
method.The following example increments the value of
i
by 100
for all documents where =i
is less than 100
:Delete Documents
To delete documents from a collection, you can use the collection’s
deleteOne
and deleteMany
methods.Pass to the methods a filter object to determine the document or documents to delete. To facilitate creating filter objects, Java driver provides the
Filters
helper. To specify an empty filter (i.e. match all documents in a collection), use an empty Document
object.The delete methods return a
DeleteResult
which provides information about the operation including the number of documents deleted.Delete a Single Document That Match a Filter
To delete at most a single document that match the filter, use the
deleteOne
method:The following example deletes at most one document that meets the filter
i
equals 110
:Delete All Documents That Match a Filter
To delete all documents matching the filter use the
deleteMany
method.The following example deletes all documents where
i
is greater or equal to 100
:Create Indexes
To create an index on a field or fields, pass an index specification document to the
createIndex()
method. An index key specification document contains the fields to index and the index type for each field:- For an ascending index type, specify
1
for<type>
. - For a descending index type, specify
-1
for<type>
.
The following example creates an ascending index on the
i
field:For a list of other index types, see Create Indexes
Additional Information
For additional tutorials (such as to use the aggregation framework, specify write concern, etc.), see Java Driver Tutorials
The following two tabs change content below.Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.
- Deploy angular apps in production - January 6, 2018
- Deploy angular app in tomcat - January 4, 2018
- PrimeNG full stack CRUD application - August 27, 2017
Previously, we saw how mongodb insert query can be used for inserting documents. This will deal with mongodb bulk insert operation which can be used to insert multiple document at once. It is like a batch process.
For inserting multiple records at once, we need a Bulk builder for the collection. Consider below code
>varbulk=db.employees.initializeUnorderedBulkOp();
- var bulk defines a variable called bulk.
- db is a default variable which refers to current database.
- employees is the collection for which we are going to create Bulk builder
- initializeUnorderedBulkOp is the methods that returns Bulk builder which will be used for mongoDB bulk insert.
Now after we got the builder, we can insert documents into builder one by one.
2 | >bulk.insert({name' 'SushantPangarkar', age:26}); > bulk.insert({name: 'AniketKulkarni', age: 26, status:'M'}); |
insert operation has not been completed yet. Right now documents are only in bulk builder. To complete mongodb bulk insert, you need to execute the bulk as below.
it will return an object of type BulkWriteResult. as below.
2 4 6 8 10 | 'writeErrors':[], 'nInserted':3, 'nMatched':0, 'nRemoved':0, }) |
This mongodb bulk insert operation confirms that 3 documents are inserted with zero errors.