1

I want to create a mongodb document structure like below.

data:[[{a:b},{b:c}],[{e:f}],[{f:g},{j:h},{i:l}]]

This structure will allow me to add new sub array element, 4th one to the existing data array which contains three sub arrays in the above example, if required.

I am able to add new sub array element using below command from mongodb shell.

db.xyz.update({'id':'A01'},{$push:{data:[]}},{})

However, I am unable to findout solution for pushing data in to respective arrays. The following command is not working.

db.xyz.update({'id':'A01'},{$push:{data[0]:{$push:{a:b}}}},{})

1 Answer 1

2

A single $push should be enough. Try this instead:

db.xyz.update({'id':'A01'}, {$push: {"data.0": {a: "b"}}})

result:

{
   "_id":ObjectId("586b907a4979a26deaacf4ad"),
   "data":[
      [
         {
            "a":"b"
         },
         {
            "b":"c"
         },
         {
            "a":"b"
         }
      ],
      [
         {
            "e":"f"
         }
      ],
      [
         {
            "f":"g"
         },
         {
            "j":"h"
         },
         {
            "i":"l"
         }
      ]
   ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

And for retrieving the first element of first array in data i am trying db.xyz.find({'id':'A01'},{data.0:{$slice:1}}) but unable to get it. i am getting all the array elements of first array while trying db.xyz.find({id:'A01'},{data:{$slice:1}}) how to get the first element of first array.
@SatyaNarayana you can do this like this: db.xyz.aggregate([{$match: {_id: "A01"}}, {$project: {data: {$arrayElemAt: [{$arrayElemAt: ["$data", 0]}, 0]}}} ])

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.