MongoDB中的对象数组内的多个对象数组 [英] Multiple arrays of objects inside array of objects in MongoDB

查看:275
本文介绍了MongoDB中的对象数组内的多个对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

资深程序员. 使用这样的MongoDb模型是否被视为不好的做法:

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.

谢谢.

推荐答案

我一般认为不是不好的习惯.如果您的模型类似于此数据结构,则以这种方式利用文档数据库来存储数据是一个不错的选择.您自然可以处理数据,并且很可能您可以直接映射到数据模型.

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:

  • 公司;
  • 部门;
  • 部门.

但是,在这种情况下,您最终将像在关系数据库中那样存储数据.因此,除一般规则外,这还取决于数据库中的数据模型和预期的查询配置文件.

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.

使用面向文档的方法,可以使用以下更新对单个部门进行精细更新:

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" } 
    ]
});

此更新使用了功能强大的新 过滤后的位置运算符功能. $[<identifier>]语法允许根据db.collection.findAndModify()方法的arrayFilters选项中表达的特定条件选择数组条目.

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.

此外,请注意,我只会在有需要的情况下应用此类优化,因为过早的优化是万恶之源. (D. Knuth).

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

这篇关于MongoDB中的对象数组内的多个对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆