我对MongoDB完全陌生,想比较NoSQL数据模型相对于其关系数据库计数器部分的查询性能。我把它写进了MongoDB shell
// Make 10 businesses
// Each business has 10 locations
// Each location has 10 departments
// Each department has 10 teams
// Each team has 100 employees
(new Array(10)).fill(0).forEach(_=>
db.businesses.insert({
"name":"Business Name",
"locations":(new Array(10)).fill(0).map(_=>({
"name":"Office Location",
"departments":(new Array(10)).fill(0).map(_=>({
"name":"Department",
"teams":(new Array(10)).fill(0).map(_=>({
"name":"Team Name",
"employees":(new Array(100)).fill(0).map(_=>({
"age":Math.floor(Math.random()*100)
}))
}))
}))
}))
})
);
然后,我EXPLAIN SELECT age,name,(and a few other fields) FROM employees WHERE age >= 50 ORDER BY age DESC
通过编写以下语句尝试了MySQL的等效功能:
db.businesses.aggregate([
{ $unwind: "$locations" },
{ $unwind: "$locations.departments" },
{ $unwind: "$locations.departments.teams" },
{ $unwind: "$locations.departments.teams.employees" },
{ $project: { _id: 0, age: "$locations.departments.teams.employees.age" } },
{ $match: { "age": { $gte: 50 }} },
{ $sort: {"age" : -1}}
]).explain("executionStats")
结果是:
“,” errmsg“:”排序超出了内存限制,为104857600字节,但未选择加入外部排序。中止操作。传递allowDiskUse:true来选择加入。“,
所以我删除了sort子句并尝试获取一个explain
。但是结果是:
TypeError:db.businesses.aggregate(...)。explain不是函数
所以我的问题是:
首先,我想知道SELECT age FROM employees WHERE age >= 50 ORDER BY age DESC
与MongoDB的聚合查询计数器部分相比的性能差异。差不多一样吗?一个会比另一个更快或更有效吗?
另外,如何修复MongoDB查询,以便获得性能详细信息以与MySQL查询计数器部分进行比较?
员工是单一实体;因此,您可能不想age
在部门,位置和团队的丰富结构中对团队成员进行如此深入的建模。拥有一个单独的employees
集合,只需执行以下操作就可以了:
db.businesses.aggregate([
{$match: {"age": {$gt: 50} }}
,{$sort: {"age": -1} }
]);
在您的businesses
收藏中,您可以拥有:
{ teams: [ {name: "T1", employees: [ "E1", "E34" ]} ] }
或者,尝试以下操作:
db.businesses.aggregate([ your pipeline] ,{allowDiskUse:true});
OP的设置为10个业务-> 10个位置-> 10个部门-> 10个团队-> 100个雇员。前三个展开会产生10000倍的数据爆炸,但最后一个则超出100倍。我们可以使用$filter
以下方法减少点击量:
db.businesses.aggregate([
{ $unwind: "$locations" },
{ $unwind: "$locations.departments" },
{ $unwind: "$locations.departments.teams" },
{$project: {
XX: {$filter: {
input: "$locations.departments.teams.employees",
as: "z",
cond: {$gte: [ "$$z.age", 50] }
}}
}}
,{$unwind: "$XX"}
,{$sort: {"XX.age":-1}}])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句