对于MongoDB 4.4.6
对于具有数组的集合-如果我使用
db.fighters.find({"close_attacks": {$size: 3}},
{"_id": 0, "biography": 0})
.pretty()
db.fighters.find({"close_attacks.2" : { $exists: true }},
{"_id": 0, "biography": 0})
.pretty()
db.fighters.find({"close_attacks.3" : { $exists: true }},
{"_id": 0, "biography": 0})
.pretty()所有的人都和平地工作
我希望使用>=# (即>=3),我做了一项研究,在许多文章中出现了两个选项,一个已经显示在上面:使用数组和#>=3的索引,另一个是使用$where
因此,在Compass中,通过_mongosh测试版,我尝试了:
db.fighters.find({$where: "this.close_attacks.length >= 3"},
{"_id": 0, "biography": 0})
.pretty()并产生
MongoError: TypeError: this.close_attacks is undefined :
@:1:15如果我删除this
db.fighters.find({$where: "close_attacks.length >= 3"},
{"_id": 0, "biography": 0})
.pretty()它产生了
MongoError: ReferenceError: close_attacks is not defined :
@:1:15少了什么或者错了什么?
发布于 2021-06-01 15:44:19
可以使用$expr运算符使用聚合运算符$gte和$size,
聚合方案首选 从MongoDB 3.6开始,
$expr操作符允许在查询语言中使用聚合表达式。
db.fighters.find({
$expr: {
$gte: [{ $size: "$close_attacks" }, 3]
}
},
{"_id": 0, "biography": 0}).pretty()MongoError:$size的参数必须是数组,但类型为:
您可以通过使用$type检查其类型来避免此类错误,
db.fighters.find({
$and: [
{ close_attacks: { $type: "array" } },
{
$expr: {
$gte: [{ $size: "$close_attacks" }, 3]
}
}
]
},
{"_id": 0, "biography": 0}).pretty()注: 从MongoDB 4.4开始,
$where不再支持带作用域的不推荐BSON类型JavaScript代码(BSON类型为15)。$where运算符只支持BSON类型字符串(BSON 2)或BSON类型JavaScript (BSON 13)。自JavaScript 4.2.1以来,不再推荐使用$where范围为BSON类型的MongoDB。
这两个块在$where中可用
https://stackoverflow.com/questions/67791958
复制相似问题