-1

Need to use insert() to add multiple subdocuments inside an empty collection. Syntax is wrong,please help.

db.boeken.insert({
    "_id":"A001",
    "auteur":"Stieg Larsson",
    "boek":["titel":"Mannen die vrouwen haten","jaartal":2005],["titel":"De vrouw die met vuur speelde","jaartal":2006]   
})

Returns :

[js] uncaught exception: SyntaxError: missing ] after element list :
@(shell):1:71

1 Answers1

0

The problem is that the array boek is malformed.

You can have 3 kinds of arrays inside a Mongo document:

1- Array of Values:

{
    "_id": "some_id",
    "some_numbers": [1, 2, 3, 4, 5],
    "some_words": ["salt", "bird", "beer"]
}

2- Array of Arrays:

{
    "_id": "some_id",
    "some_arrays": [
        [1, 2, 3, 4, 5],
        ["salt", "bird", "beer"]
    ]
}

3- Array of documents (that's your case):

{
    "_id": "some_id",
    "boek":[
        {
            "titel":"Mannen die vrouwen haten",
            "jaartal":2005
        },
        {
            "titel":"De vrouw die met vuur speelde",
            "jaartal":2006
        }
   ]   
}

That said, if you want to use key:value for the elements of the array boek, that means that you have an array of documents. The problem with your code is that you are missing the {} for each element of the array.

So, in your case, the correct code would be:

db.boeken.insert({
    "_id":"A001",
    "auteur":"Stieg Larsson",
    "boek":[
        {
            "titel":"Mannen die vrouwen haten",
            "jaartal":2005
        },
        {
            "titel":"De vrouw die met vuur speelde",
            "jaartal":2006
        }
    ]   
})
Caconde
  • 4,177
  • 7
  • 35
  • 32