How to insert multiple documents?

0119

To insert multiple documents into a MongoDB collection, you can use the insertMany() method. Here's how you can do it using the MongoDB shell or through a command executed in a Kubernetes pod.

Using MongoDB Shell

If you are using the MongoDB shell, you can insert multiple documents like this:

db.collectionName.insertMany([
  { field1: "value1", field2: "value2" },
  { field1: "value3", field2: "value4" },
  { field1: "value5", field2: "value6" }
])

Example

For example, if you want to insert multiple messages into a messages collection, you can do it as follows:

db.messages.insertMany([
  { message: "First message" },
  { message: "Second message" },
  { message: "Third message" }
])

Using kubectl exec

If you want to execute this command inside a Kubernetes pod named db, you can use the following command:

kubectl exec db -it -- mongo testdb --quiet --eval \
  'db.messages.insertMany([
    { "message": "First message" },
    { "message": "Second message" },
    { "message": "Third message" }
  ])'

Expected Output

The output will indicate whether the insertion was successful, typically showing the number of documents inserted and their IDs.

If you have any further questions or need additional examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!