如何在MongoDB中使用查询功能?

问题描述 投票:1回答:1

我有MongoDB。collection_name有一些带有key: key_namevalue: "1 ff 42"的文档。如果仅我知道该如何找到该文档,值中的所有数字等于142?我可以从字符串中提取所有数字,然后在Integer中对其进行“转换”。

var string_with_numbers = "1 ff 42";
number_array = string_with_numbers.match(/[0-9]+/g);

// 142 by Integer
result = parseInt(number_array.join(''));

但是,如何从值中所有数字等于142的集合中提取所有文档?


db.collection_name.find(
    {
        key_name: {...}
    }
    );
javascript mongodb
1个回答
0
投票

这有点棘手,但是您可以通过这种聚合来实现您的要求:

db.collection_name.aggregate([
    {
        "$addFields": {
            "results": {
                "$regexFindAll": {
                    "input": "$value",
                    "regex": /\d+/
                }
            }
        }
    },
    {
        "$project": {
            "number": {
                "$toInt": {
                    "$reduce": {
                        "input": "$results",
                        "initialValue": "",
                        "in": {
                            "$concat": ["$$value", "$$this.match"]
                        }
                    }
                }
            }
        }
    },
    {
        "$match": {
            "number": 142
        }
    }
])

数据:

> db.collection_name.find()
{ "_id" : ObjectId("5dfbf14671f3d8949c44881c"), "value" : "1rt 42" }
{ "_id" : ObjectId("5dfbf14671f3d8949c44881d"), "value" : "1 4sd 2" }
{ "_id" : ObjectId("5dfbf14671f3d8949c44881e"), "value" : "14 e 6" }

第一阶段$addFileds之后将具有以下内容:

{
    "_id" : ObjectId("5dfbf14671f3d8949c44881c"),
    "value" : "1rt 42",
    "results" : [
        {
            "match" : "1",
            "idx" : 0,
            "captures" : [ ]
        },
        {
            "match" : "42",
            "idx" : 4,
            "captures" : [ ]
        }
    ]
}
.
.

然后在第二阶段$project之后:

{ "_id" : ObjectId("5dfbf14671f3d8949c44881c"), "number" : 142 }
{ "_id" : ObjectId("5dfbf14671f3d8949c44881d"), "number" : 142 }
{ "_id" : ObjectId("5dfbf14671f3d8949c44881e"), "number" : 146 }

最后使用$match,您将获得预期的结果:

{ "_id" : ObjectId("5dfbf14671f3d8949c44881c"), "number" : 142 }
{ "_id" : ObjectId("5dfbf14671f3d8949c44881d"), "number" : 142 }
© www.soinside.com 2019 - 2024. All rights reserved.