ediblecode
ediblecode

Reputation: 11971

Inserting multiple nested objects with MongoDB

I'm very new to MongoDB so forgive me if this question isn't worded correctly. I know how to insert into the database, and I also know that I can have a nested object and know how to install that. I have:

Questions.insert({ Order:1, Question: "What type of property is it?", 
    Answers: { Order: 1, Answer: "House" }});

I hope from the above statement you can see that I'm aiming to try and insert multiple answers for this question (this may be where I'm going wrong, is this the right approach?). So looking at the above statement, I thought that I could insert multiple answers as such:

Questions.insert({ Order:1, Question: "What type of property is it?", 
    Answers: [{ Order: 1,    Answer: "House" }, 
             { Order: 2, Answer: "Flat" }, 
             { Order: 3, Answer: "Bungalow" }, 
             { Order: 4, Answer: "Maisonette }]
});

SyntaxError: Unexpected token ILLEGAL

Upvotes: 2

Views: 8078

Answers (2)

potatosalad
potatosalad

Reputation: 4887

You are missing a " at the end of Maisonette which is where the error is coming from.

{ Order: 4, Answer: "Maisonette }]

Otherwise your query is on the right track for inserting embedded documents.

Upvotes: 5

Jim Dagg
Jim Dagg

Reputation: 2032

Your answers sub-document is kind of acting like an array. There are two possibilities you could use to store multiple answers in each question:

1) Just use an array:

Questions.insert({order : 1, 
    question : "What type of property is it?", 
    answers : [ "House", "Flat", "Bungalow", "Maisonette" ]
    });

2) The way MongoDB will sometimes internally store arrays is to simply use an ordinal as the key to each sub-document, like so:

Questions.insert({order : 1, 
    question : "What type of property is it?", 
    answers : {"1" : "House",
               "2" : "Flat",
               "3" : "Bungalow",
               "4" : "Maisonette"}
    });

Upvotes: 1

Related Questions