Multiple arrays of objects inside array of objects

2019-08-03 21:35发布

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.

标签: mongodb nosql
1条回答
你好瞎i
2楼-- · 2019-08-03 21:56

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).

查看更多
登录 后发表回答