2

In MongoDB,

I know how to insert objects, such as:

db.animals.insert(
    {"name": "cat"},
    {"name" : "dog"},
    {"name" : "zebra"}
)

But how do I insert an array instead? So I don't have to define a key/value pair? Such as:

db.animals.insert([
    "cat",
    "dog",
    "zebra"
])

This last one doesn't work.

The reason why I want to insert an array, is that I want to get the following data when I do a db.animals.find({})

"cat", "dog", "zebra"

1 Answer 1

2

You cannot do that, as the smallest unit of MongoDB is the document, and as you may guess an array is not a document. As an alternative, you could go this way.

db.animals.insert({
    animals: [
    "cat",
    "dog",
    "zebra"
    ]
)

And then you will have:

> db.animals.find({})
{_id: <somethig>, animals: ["cat", "dog", "zebra"]}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.