Eva*_*tis 13 javascript mongodb mongodb-query aggregation-framework
这个查询有什么问题?我试图在mongodb服务器上运行它并收到如下错误 - "异常:错误的查询:BadValue未知的顶级操作符:$ gte".有人能告诉我它有什么问题吗?
db.scores.aggregate([
{
$match: {
$or: [
{ $gte: [ "$score", 30 ] },
{ $lte: [ "$score", 60 ] }
]
}
},
{
$group: {
_id: "$gamer",
games: { $sum: 1 }
}
}
])
Run Code Online (Sandbox Code Playgroud)
样本数据 :
{
"_id" : "545665cef9c60c133d2bce72",
"score" : 85,
"gamer" : "Latern"
}
/* 1 */
{
"_id" : "545665cef9c60c133d2bce73",
"score" : 10,
"gamer" : "BADA55"
}
/* 2 */
{
"_id" : "545665cef9c60c133d2bce74",
"score" : 62,
"gamer" : "BADA55"
}
/* 3 */
{
"_id" : "545665cef9c60c133d2bce75",
"score" : 78,
"gamer" : "l00ser"
}
/* 4 */
{
"_id" : "545665cef9c60c133d2bce76",
"score" : 4,
"gamer" : "l00ser"
}
/* 5 */
{
"_id" : "545665cef9c60c133d2bce77",
"score" : 55,
"gamer" : "FunnyCat"
}
Run Code Online (Sandbox Code Playgroud)
Nei*_*unn 16
你做错了.应该:
db.scores.aggregate([
{ "$match": {
"score": { "$gte": 30, "$lte": 60 }
}},
{ "$group": {
"_id": "$gamer",
"games": { "$sum": 1 }
}}
])
Run Code Online (Sandbox Code Playgroud)
哪个是指定"范围"查询的正确方法,其中实际条件是"和",因此指定了操作数"之间".
从 MongoDB 3.6 版开始,您可以使用$expr在查询中使用聚合表达式。所以查询可以改写为:
db.scores.aggregate([
{
$match: {
$expr: {
$or: [
{ $gte: ["$score", 30] },
{ $lte: ["$score", 60] }
]
}
}
},
{
$group: {
_id: "$gamer",
games: { $sum: 1 }
}
}
]);
Run Code Online (Sandbox Code Playgroud)