这是您可以使用的方法。每个用户的所有费用与用户一起存储,如示例文档中所示。用户的费用存储在一个数组中,并且每个数组元素都是费用子文档(包含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