mongodb中的三级关系

我有三级关系数据库,第一个表是user,例如,我有user A,B。 }}有user,例如食物,租金支出。最终每个expense type都有自己的费用。

现在该结构如下:expense type

如果我在 MYSQL 中设计此数据库,则会创建三个不同的表并在它们之间建立关系,并且很容易就能找到每个 的支出用户

user ==> expense_type ==> expense

但是我的问题是,我必须使用 Mongodb(我在Express中使用Mongoose) ,现在的问题是在中设计此数据库的最佳实践是什么> Mongodb ?以及如何为所有//mysql query to return all expenses for user A select expense.* from user,expense,expense_type where user.id=expense_type.user_id and expense.type_id=expense_type.id and user.id=1 //id of user A 返回全部expenses

感谢您的帮助:)

lqlzzm156 回答:mongodb中的三级关系

这是您可以使用的方法。每个用户的所有费用与用户一起存储,如示例文档中所示。用户的费用存储在一个数组中,并且每个数组元素都是费用子文档(包含ensemise_type和amount)。这样,您将只需要数据模型中的一个集合。

user_expenses集合中抽取文档样本(假设_id与用户ID相同):

{
        "_id" : 1,"exp" : [
                {
                        "exp_type" : "food","amt" : 25
                },{
                        "exp_type" : "rent","amt" : 500
                }
        ]
},{
        "_id" : 2,"amt" : 18
                },{
                        "exp_type" : "gas","amt" : 48
                },{
                        "exp_type" : "misc","amt" : 33
                }
        ]
}


查询:

我们如何查询该集合?这是一些示例用例。

  

(1)如何退回任何用户的所有费用?

db.user_exp.find( {_id: 1 } )

输出:

{ "_id" : 1,"exp" : [ { "exp_type" : "food","amt" : 25 },{ "exp_type" : "rent","amt" : 500 } ] }


(2)如何获得用户的所有费用之和?

db.user_exp.aggregate( [
    { $match: { _id: 1 } },{ $unwind: "$exp" },{ $group: { _id: "$_id","sum_exp": { $sum: "$exp.amt" } } }
] )

输出:

{ "_id" : 1,"sum_exp" : 525 }


(3)查询用户的特定费用类型:

db.user_exp.aggregate( [
    { $match: { _id: 2 } },{ $match: { $or: [ { "exp.exp_type": { $eq: "food" } },{"exp.exp_type": { $eq: "misc" } } ] } }
] )

输出:

{ "_id" : 2,"exp" : { "exp_type" : "food","amt" : 18 } }
{ "_id" : 2,"exp" : { "exp_type" : "misc","amt" : 33 } }



数据建模:

MongoDB的灵活模式允许根据用例或应用程序需求设计数据(这与关系数据库(SQL)中的方法不一样,您必须使用相当严格的方法)。

要了解有关数据库设计(或数据建模)的更多信息,请参阅此MongoDB文档,网址为Data modeling introduction

本文链接:https://www.f2er.com/3093286.html

大家都在问