Inserting a Document into a MongoDB Collection
To insert a document in MongoDB, you can use the insert()
method on a collection. The method takes a single argument, which is the document to insert. Here's an example of how to insert a document with multiple key-value pairs:
db.collectionName.insert({
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4"
})
In this example, db
is the name of the current database, collectionName
is the name of the collection in which you want to insert the document, and insert
is the MongoDB command to insert a document in the collection. Each key-value pair within the document is enclosed in curly braces {}.
Additionally, you can use insertOne
or insertMany
methods, depending on whether you want to insert a single document or multiple documents at once.
db.collectionName.insertOne({
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4"
})
db.collectionName.insertMany([ { "key1": "value1", "key2": "value2" }, { "key3": "value3", "key4": "value4" }])
This will insert the documents in the collection.
You may also like
Deleting a Collection in MongoDB
Delete a MongoDB collection using drop() or db.runCommand( { drop: "...
Continue readingGuide to Dropping MongoDB Collections Safely
This blog post provides a step-by-step guide on how to drop a MongoD...
Continue reading