如何查找数组的范围大于或等于其等效整数



我正在使用MongoDB 6:

例如,我想在一个数组中检查一个大于1且小于3的数字,该数组既包含整数形式的数字,也包含字符串形式的数字。

以下是示例数据集:

> db.test.find()
{ "_id" : ObjectId("62ed3cfbeadf50344d622dd0"), "test" : 1, "name" : "Testing Alpha", "array" : [ 1, 2, 3 ] }
{ "_id" : ObjectId("62ed4798eadf50344d622dd1"), "array" : [ "1", "2" ] }
{ "_id" : ObjectId("62ed47f5eadf50344d622dd2"), "array" : [ "1111", "22242" ] }
{ "_id" : ObjectId("62ed4826eadf50344d622dd3"), "array" : [ "11119", "222438", "31738234", "15", "41", "141" ] }

我试图找到引号和正整数中包含的数字2或1到3之间的数字。如何获取包含2或"0"的所有数组;2〃;使用$gt和$lt运算符。

所以基本上,我试图找到2或";2〃;在数组字段中,但我需要将字符串转换为int,不知道如何做到这一点。因此,应该只找到查找中的前两项。

以下是我失败的发现:

db.test.find({array: {$gt: "1", $lt: "3"}})
db.test.find({array: {$gt: 1, $lt: 3}})
db.test.find({$and: [array: {$gt: 1, $lt 3}, array: {$gt: "1", $lt "3"}]})
db.test.find({$or: [{"array": {$gt: 1, $lt: 3}}, {"array": {$gt: "1", $lt: "3"}}]})
db.test.find({$and: [{"array": {$gt: 1, $lt: 3}}, {"array": {$gt: "1", $lt: "3"}}]})

一个选项是使用具有$filter$toInt:的聚合管道

db.collection.aggregate([
{$set: {
arrayInt: {
$filter: {
input: "$array",
cond: {
$and: [
{$lt: [{$toInt: "$$this"}, 3]},
{$gt: [{$toInt: "$$this"}, 1]}
]
}
}
}
}
},
{$match: {"arrayInt.0": {$exists: true}}},
{$unset: "arrayInt"}
])

看看它是如何在操场上工作的例子

最新更新