Mongodb find operation in embedded document

34 Views Asked by At

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

There are 1 best solutions below

0
We do the best for You On

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