-1

My requirement is to create a embedded document in mongodb collection through Java and here's the structure

folder

{

_id: String, // location id

documentVersion: int,

locationDisplayName: String;

displayName: String,

subfolders: [

    {

        dispalyName: String,

        subcategories: [

            /// For Catgeory type

            {

                displayName: String,

                subcategories: [

                ],

                items: [

                ]

            },

        ],

        items: [

            {

                displayName: String,

                itemId: String,

                name: String,

                code: String

            },

            ...



        ],

        itemId: String,

        name: String,

        code: String

    }

],

items: [

    {

        displayName: String,

        itemId: String,

        name: String,

        code: String

    },

    ..

]

}

I am able to check the parent folder and insert subfolder at 2 levels using element match. However my sub folder can go upto level 6. How can I do the match and insert folder at correct level and also insert items into the folder

1
  • Please provide enough code so others can better understand or reproduce the problem. Commented Mar 21, 2024 at 7:30

1 Answer 1

0

As you know, the nested array structure in MongoDB is updated and referenced using the positional operator.

It has been documented in the page enclosed. You may also see an example below, quoted from the same documentation. This document was originally included in an another Stack-over-flow answer which is also enclosed.

Since these documentation is based on an older version of MongoDB, request you may refer to the latest documentation as well. You can see that too enclosed.

//Update all matching documents in nested array**
db.coll.update({}, {$set: {“a.$[i].c.$[j].d”: 2}}, {arrayFilters: [{“i.b”: 0}, {“j.d”: 0}]})
Input: {a: [{b: 0, c: [{d: 0}, {d: 1}]}, {b: 1, c: [{d: 0}, {d: 1}]}]}
Output: {a: [{b: 0, c: [{d: 2}, {d: 1}]}, {b: 1, c: [{d: 0}, {d: 1}]}]}

Positional Operator Matching Nested Arrays

Mongodb update deeply nested subdocument

Update Nested Arrays in Conjunction with $[]

Thanks WeDoTheBest4You

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.