Kuzunoha-NEのブログ

プログラミングなどの勉強をしてます

【TypeScript】Mongodbが持つ数字を正規表現で取ろうとしたら出来なかった

こんばんは葛の葉です

mongodbのフィールドにある数字を取り出そうと正規表現を使ったのですが、全くヒットせず、正規表現の書き方が間違ってるのかなんなのかがわからず、暫く格闘を続けるというアホみたいなことをしていました。

MongoDBの公式について

Provides regular expression capabilities for pattern matching strings in queries. MongoDB uses Perl compatible regular expressions (i.e. “PCRE” ) version 8.42 with UTF-8 support.

docs.mongodb.com

やりたかったこと

{ name: 'kuzunoha', status: 200 },
{ name: 'pontaro',  status: 230 },
{ name: 'daigoro',  status: 309 }

こういうデータに対してstatusの3桁目が2のデータを取得してきたかった。

import { MongoClient } from "mongodb";

const uri = 'mongodb://127.0.0.1:27017';
const dbName = '__test__';
const collectionName = 'test';

(async()=>{
    const client = await MongoClient.connect(uri, { useUnifiedTopology: true });
    const __test__ = client.db(dbName);
    
    const cursor = __test__.collection(collectionName).find({
        status: /2[0-9]./
    });
    
    while(await cursor.hasNext()){ // 検索がヒットしないのでwhileが動作しない
        const data = await cursor.next();
        console.log(data.name);
    };

    await __test__.collection(collectionName).drop();
    await client.close()
})();

StackOverFlowには

ちょうど同じところで躓いている人がいたみたい。文字列は正規表現出来るけど、数字は正規表現で広くことが出来ないみたい。aggregateを使うことで文字列となるフィールドを追加して、そのフィールドに正規表現を使うようにします。

stackoverflow.com

こうするみたい

- const cursor = __test__.collection(collectionName).find({
-     status: /2[0-9]./
- });

+ const cursor = __test__.collection(collectionName).aggregate([
+     {$addFields: {statusStr: {$toString: '$status'}}},
+     {$match:{statusStr:/2[0-9]./}}
+ ]);

今回のソースコード

github.com