Introduction
MongoDB is a popular NoSQL database that stores data in collections, which are analogous to tables in a relational database. To import data into a MongoDB collection, we can use the mongoimport
command-line tool or utilize MongoDB drivers in various programming languages. This documentation will cover both methods with examples.
Method 1: Using mongoimport command-line tool
MongoDB provides the mongoimport
command-line tool, which allows us to import data from a JSON, CSV, or TSV file into a MongoDB collection.
Syntax:
cssmongoimport --db <database_name> --collection <collection_name> --file <file_path> --jsonArray
Explanation:
--db
: Specifies the database where the collection resides.--collection
: Specifies the target collection where the data will be imported.--file
: Specifies the path of the file containing the data to be imported.--jsonArray
: Specifies that each document in the input file should be treated as a separate JSON object.
Example:
Let's say we have a file named users.json
containing the following JSON data:
json[
{ "name": "John", "age": 30, "email": "john@example.com" },
{ "name": "Jane", "age": 25, "email": "jane@example.com" }
]
To import this data into a collection named usersdb
in the database mydb
, we would run the following command in the terminal:
cssmongoimport --db mydb --collection usersdb --file users.json --jsonArray
Method 2: Using MongoDB Drivers
MongoDB provides official drivers for various programming languages, such as Python, Node.js, Java, etc. We can use these drivers to import data programmatically.
Example using Python:
First, make sure you have installed the pymongo library:
bashpip install pymongo
pythonimport pymongo
import json
# Connection to MongoDB server
client = pymongo.MongoClient("mongodb://localhost:27017/")
# Accessing the database
db = client["mydb"]
# Accessing the collection
collection = db["usersdb"]
# Load data from JSON file
with open("users.json") as file:
data = json.load(file)
# Insert data into the collection
result = collection.insert_many(data)
# Print the inserted document IDs
print(result.inserted_ids)
Explanation:
- We first import the necessary libraries (pymongo and json).
- Establish a connection to the MongoDB server running on
localhost
and port27017
. - Access the database named
mydb
. - Access the collection named
usersdb
. - Load data from the
users.json
file using Python'sjson.load()
method. - Use
insert_many()
to insert the data into the collection. - Print the IDs of the inserted documents.
This concludes the documentation on importing data into a MongoDB collection. Whether you prefer using the mongoimport
tool or MongoDB drivers, both methods allow you to easily populate your collections with data from various sources.
0 Comments