Wednesday 16 June 2021

MongoDB: mongoimport: Import documents from a file

‘mongoimport’ command is used to import the documents from a file.

 

Append data to the existing collection

mongoimport {file_path_to_import} -d {database_name} -c {collection_name} --jsonArray

 

Drop the existing data from the collection and import the data from the file

mongoimport {file_path_to_import} -d {database_name} -c {collection_name} --jsonArray --drop

 

Let’s see it with an example. For example, employee collection has following data.

> db.employee.find()
{ "_id" : ObjectId("60c97d29fc455868b4f32101"), "firstName" : "Krishna", "lastName" : "Gurram", "age" : 31 }
{ "_id" : ObjectId("60c97dbcfc455868b4f32102"), "firstName" : "Siva", "lastName" : "Ponnam", "age" : 34 }

 

Now I want to append data to the employee collection from

 

emp1.json

[
	{
		"firstName" : "Chamu",
		"lastName" : "Gurram"
	},
	{
		"firstName" : "Harini",
		"lastName" : "Maj"
	}
]

 

$mongoimport /Users/Shared/mongodb/emp1.json -d sample -c employee --jsonArray
2021-06-16T15:53:48.372+0530	connected to: mongodb://localhost/
2021-06-16T15:53:48.377+0530	2 document(s) imported successfully. 0 document(s) failed to import.

Let’s query employee collection again.

> db.employee.find()
{ "_id" : ObjectId("60c97d29fc455868b4f32101"), "firstName" : "Krishna", "lastName" : "Gurram", "age" : 31 }
{ "_id" : ObjectId("60c97dbcfc455868b4f32102"), "firstName" : "Siva", "lastName" : "Ponnam", "age" : 34 }
{ "_id" : ObjectId("60c9d1349f878ae6f54110f0"), "firstName" : "Harini", "lastName" : "Maj" }
{ "_id" : ObjectId("60c9d1349f878ae6f54110f1"), "firstName" : "Chamu", "lastName" : "Gurram" }

 

Drop all the documents from employee collection and add documents from emp2.json file

emp2.json

[
	{
		"firstName" : "Venkatesh",
		"lastName" : "Battula"
	},
	{
		"firstName" : "Maruthi",
		"lastName" : "Bolisetty"
	}
]

 

$mongoimport /Users/Shared/mongodb/emp1.json -d sample -c employee --jsonArray --drop
2021-06-16T15:57:43.569+0530	connected to: mongodb://localhost/
2021-06-16T15:57:43.570+0530	dropping: sample.employee
2021-06-16T15:57:43.724+0530	2 document(s) imported successfully. 0 document(s) failed to import.

 

Let’s query employee collection again.

> db.employee.find()
{ "_id" : ObjectId("60c9d21f304ce763b168f548"), "firstName" : "Chamu", "lastName" : "Gurram" }
{ "_id" : ObjectId("60c9d21f304ce763b168f549"), "firstName" : "Harini", "lastName" : "Maj" }

 

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment