Mongo查找值中包含撇号的字符串

时间:2019-07-06 15:12:36

标签: php mongodb

该字段值在mongo集合字段recording.title中包含带有撇号“我永远不会看到的梦想”的字符串

$updateResult = $collection->findOneAndUpdate(
        [
            'recording-id'          => $out['recording']->id
        ],
        ['$set'  => [ 
            'recording'         => [
                'id'            => $out['recording']->id,
                'title'         => $out['recording']->title,
                'score'         => $out['recording']->score,
                'length'        => $out['recording']->length,
                'release-count' => count($out['recording']->releases)
                ]
        ],
        ['upsert' => true]);

当一个记录不存在时,这会正确地在我的收藏夹中创建我的记录,并且在再次运行时不会创建多个新记录,但是当我搜索标题“我永远不会看到的梦想”时,找不到匹配项。

我的搜索代码示例:

$t = "Dreams I'll Never See";
$a = "Molly Hatchet";

$cursor = $collection->find(
                    ['$and' => [
                        [ 'recording.title'  =>  $t ],
                        [ 'artist.name'       => $a ]
                    ]
                    ],
                    ['projection'   => [
                        'recording'     =>1,
                        'release'       =>1,
                        'artist'        =>1,
                        'release-group' =>1
                    ],
                    ['limit' => 1]
                ]
    );

我整个上午都在Google上搜索,但似乎无法正常工作。

Mongo shell显示存储的记录字段:

"recording" : {
        "id" : "446ff065-a9bb-4171-a0d9-dbfa29661f99",
        "title" : "Dreams I’ll Never See",
        "score" : 100,
        "length" : 428000,
        "release-count" : 13
    },

1 个答案:

答案 0 :(得分:0)

此查询现在返回正确的匹配项:

$cursor = $collection->find(
                    ['$and' => [
                        [ 'recording.title'  =>  new MongoDB\BSON\Regex($t, 'ig') ],
                        [ 'artist.name'       => new MongoDB\BSON\Regex($a, 'ig')  ]
                    ]
                    ],
                    ['projection'   => [
                        'recording'     =>1,
                        'release'       =>1,
                        'artist'        =>1,
                        'release-group' =>1
                    ],
                    ['limit' => 1]
                ]
    );

正则表达式模式就是解决方案。如果有人知道更好的方法,我将全神贯注地看到它。