How to insert new documents into a MongoDB collection in your database?

MongoDBDatabaseBig Data Analytics

To insert new documents into a MongoDB collection, you need to use insert() method or save() method.

Case 1: Using insert() method.

The syntax is as follows:

db.yourCollectionName.insert(yourDocument);

Case 2: Using save() method.

The syntax is as follows:

db.yourCollectionName.save(yourDocument);

In the above syntax, if your collection name does not exist then MongoDB will create a new collection and insert the document in the collection.

The query to insert new documents is as follows for both the cases discussed above.

Case 1: Using insert() method. The query is as follows:

> db.userInformation.insert({
   ... "Name":"John",
   ... Age:30,
   ... isStudent:false,
   ... "Subjects":["Introduction to java","Introduction to MongoDB"]
   ...
});

The following is the output:

WriteResult({ "nInserted" : 1 })

Above, I already had a collection name ‘userInformation’. In this case MongoDB will not create any collection name since it already exist.

Case 2: The following is the query to insert documents with the help of save():

> db.employee.save({"EmployeeName":"Larry",Salary:180000,Age:25,
   ... "Address":({"CountryName":"US","CityName":"New York"})
   ... });

The following is the output:

WriteResult({ "nInserted" : 1 })

In the above query, we do not have a collection name ‘employee’. Therefore, MongoDB will create a collection with the name ‘employee’ and insert documents in the newly created collection.

To display all collection names now, use the show command. The query is as follows:

> show collections;

The following is the output:

employee
userInformation

Yes, we have employee collection now, even if we did not created it using createCollection(). MongoDB has created a ‘employee’ collection for us as we saw above.

raja
Published on 18-Mar-2019 15:07:08
Advertisements