Multiple arrays of objects inside array of objects in MongoDB

只愿长相守 提交于 2019-12-24 13:33:57

问题


Fellow programmers. Is it considered as a bad practice to use such MongoDb model:

{
    companyId: '',
    companyName: '',
    companyDivisions: [
        {
            divisionId: '',
            divisionName: '',
            divisionDepartments: [
                {
                    departmentId: '',
                    departmentName: ''
                },
                ...
            ]
        },
        ...
    ],
},
...

Because right now it's getting complicated to update certain departments.

Thanks.


回答1:


I don't think this is a bad practice generally speaking. If your model resembles this data structure it is a good choice storing data this way, leveraging a document database. You can naturally handle data and most likely you have a direct map onto your data model.

Another choice would be to have three different collections:

  • companies;
  • divisions;
  • departements.

However, in this case you would end up storing data as you would do in a relational database. Thus, more than a general rule, it is a matter of data model and expected query profile on your database.

Edit: using MongoDb 3.6+

Using your document oriented approach, a single department can be granularly updated using the following update:

db.companies.findAndModify(
{
    query: {
        "companyId": "yourCompanyId"
    },
    update: {
        $set : { "companyDivisions.$[element1].divisionDepartments.$[element2].divisioneName": "yourNewName" }
    },
    arrayFilters: [ 
        { "element1.divisionId": "yourDivisioneId" },
        { "element2.departmentId": "yourDepartementId" } 
    ]
});

This update uses the new powerful filtered positional operator feature introduced by MongoDB v3.6. The $[<identifier>] syntax allows to select an array entry based on a specific condition expressed in the arrayFilters option of the db.collection.findAndModify() method.

Note that in case the condition matches multiple array items, the update affects all such items, thus allowing for multiple updates as well.

Furthermore, note that I would apply such an optimization only in case of need, since premature optimization is the root of all evil. (D. Knuth).



来源:https://stackoverflow.com/questions/48967418/multiple-arrays-of-objects-inside-array-of-objects-in-mongodb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!