以复杂的方式在 No-SQL MongoDB 中写下 $subtract
Writting down $subtract in No-SQL MongoDB in a sophisticated way
我正在做 MongoDB 学院,对于这个问题:
What is the difference between the number of people born in 1998 and the number of people born after 1998 in the sample_training.trips collection?
最简单的方法是(他们希望您回答的方式):
db.trips.find({"birth year":1988}).count()
和:
db.trips.find({"birth year":{$gt:1988}}).count()
然后,手动计算。
我不熟悉编程和代码语法,但想知道一个复杂的方法,可以改进类似下面的代码。
db.trips.aggregate({$subtract:[db.trips.find({"pop":1988}).count(),db.trips.find({"pop":{$gt:1988}}).count()]})
注意:Atlas“免费订阅者”不允许在查询中使用 $subtract,所以我什至测试了它是否有效。
您也可以使用以下方法对 1998 年和 1988 年之后出生的人数进行分组,同样只需一个聚合查询。
聚合流水线阶段:
- Select 仅那些
birth year
等于或大于 1988
的记录
- 按
birth year
对人数进行分组
- 在
$project
阶段 使用 $cond
运算符向每条记录添加新字段 born_on
- 通过新添加的字段
born_on
再次对记录进行分组,现在将只为您提供计数为 on_1988
和 after_1988
的两条记录
查询如下
db.trips.aggregate([
{
"$match":{
"birth year":{
"$gte":1988
}
}
},
{
"$group":{
"_id":"$birth year",
"count":{
"$sum":1
}
}
},
{
"$project":{
"count":"$count",
"born_on":{
"$cond":[
{
"$eq":[
"$_id",
1988
]
},
"on_1988",
"after_1988"
]
}
}
},
{
"$group":{
"_id":"$born_on",
"total":{
"$sum":"$count"
}
}
}
])
** 可能有另一种更优化的方法来实现相同的结果,但这也有效
更简单的使用方式:
(查询 1)-(查询 2)
db.trips.find({"birth year":{"$gt":1998}}).count() - db.trips.find({"birth year":1998}).count()
您将得到整数形式的结果
6
您可以使用以下查询来获取此值:
db.trips.find( { "birth year": { "$gt": 1998 } } ).count()
db.trips.find( { "birth year": 1998 } ).count()
使用$gt
而不是$gte
运算符排除所有1998年出生的人,然后使用隐式相等查看1998年出生的人有多少,然后将两个值相减得到差值.
我正在做 MongoDB 学院,对于这个问题:
What is the difference between the number of people born in 1998 and the number of people born after 1998 in the sample_training.trips collection?
最简单的方法是(他们希望您回答的方式):
db.trips.find({"birth year":1988}).count()
和:
db.trips.find({"birth year":{$gt:1988}}).count()
然后,手动计算。
我不熟悉编程和代码语法,但想知道一个复杂的方法,可以改进类似下面的代码。
db.trips.aggregate({$subtract:[db.trips.find({"pop":1988}).count(),db.trips.find({"pop":{$gt:1988}}).count()]})
注意:Atlas“免费订阅者”不允许在查询中使用 $subtract,所以我什至测试了它是否有效。
您也可以使用以下方法对 1998 年和 1988 年之后出生的人数进行分组,同样只需一个聚合查询。
聚合流水线阶段:
- Select 仅那些
birth year
等于或大于1988
的记录
- 按
birth year
对人数进行分组
- 在
$project
阶段 使用 - 通过新添加的字段
born_on
再次对记录进行分组,现在将只为您提供计数为on_1988
和after_1988
的两条记录
$cond
运算符向每条记录添加新字段 born_on
查询如下
db.trips.aggregate([
{
"$match":{
"birth year":{
"$gte":1988
}
}
},
{
"$group":{
"_id":"$birth year",
"count":{
"$sum":1
}
}
},
{
"$project":{
"count":"$count",
"born_on":{
"$cond":[
{
"$eq":[
"$_id",
1988
]
},
"on_1988",
"after_1988"
]
}
}
},
{
"$group":{
"_id":"$born_on",
"total":{
"$sum":"$count"
}
}
}
])
** 可能有另一种更优化的方法来实现相同的结果,但这也有效
更简单的使用方式: (查询 1)-(查询 2)
db.trips.find({"birth year":{"$gt":1998}}).count() - db.trips.find({"birth year":1998}).count()
您将得到整数形式的结果
6
您可以使用以下查询来获取此值:
db.trips.find( { "birth year": { "$gt": 1998 } } ).count()
db.trips.find( { "birth year": 1998 } ).count()
使用$gt
而不是$gte
运算符排除所有1998年出生的人,然后使用隐式相等查看1998年出生的人有多少,然后将两个值相减得到差值.