首页 > 解决方案 > mongodb C驱动程序如何使用正则表达式通过_id过滤更改流

问题描述

要使用 mongodb C 驱动程序通过正则表达式查找,这有效(也仅限于使用“$projection”的某些字段),使用 bson_append_regex:

sprintf(regexstring,"^%04X.*", regid);

查询=bson_new(); bson_append_regex(查询,“_id”,-1,正则表达式,NULL);

// 单个字段的投影 opts=BCON_NEW("projection","{", fieldstring0, BCON_BOOL(true), fieldstring1, BCON_BOOL(true), "}");
cursor=mongoc_collection_find_with_opts(ctx->m_Collection,query,opts,NULL);

如何将正则表达式与 mongoc_collection_watch 一起使用?

此示例使用“聚合管道”“$match”:https ://docs.mongodb.com/manual/changeStreams/

pipeline = BCON_NEW ("pipeline",
                     "[",
                     "{",
                     "$match",
                     "{",
                     "fullDocument.username",
                     BCON_UTF8 ("alice"),
                     "}",
                     "}",
                     "{",
                     "$addFields",
                     "{",
                     "newField",
                     BCON_UTF8 ("this is an added field!"),
                     "}",
                     "}",
                     "]");

有没有 _id 键的正则表达式更改流的 C 驱动程序的示例?

在 php 中这有效:

    $client=new MongoDB\Client($uri);       
    $collection = $client->test->my_collection;     
    $regex = new MongoDB\BSON\Regex('^'.$user->requestedregister);
    $pipeline = [ ['$match' => ['documentKey._id' => $regex]]];     
    $user->changeStream = $collection->watch($pipeline);

如何在 C 驱动程序中执行此操作?

这适用于 mongo shell:

db.my_collection.aggregate(
    [ { $match : { _id : "0FFC0006" } } ]
);

这有效:

bson_t opts= BSON_INITIALIZER;
pipeline = BCON_NEW ("pipeline",
                     "[",
                     "{",
                     "$match",
                     "{",
                     "operationType",
                     "{",
                     "$in",
                     "[",
                     "update",
                     "]",
                     "}",
                     "documentKey._id",
                     **"0FFC0006",// <------- how to use a regex here** ?
                     "}",
                     "}",
                     "]");
    
BSON_APPEND_INT64 (&opts, "maxAwaitTimeMS", 60*60 * 1000);
stream = mongoc_collection_watch (collection, pipeline, &opts);

更新:这似乎工作:

sprintf(regexstring,"^%04X.*", ctx->m_RequestedRegister);
pipeline = BCON_NEW ("pipeline",
                 "[",
                 "{",
                 "$match",
                 "{",
                 "documentKey._id",
                 "{",
                 "$regex",
                 regexstring,
                 "$options",
                 "si",
                 "}",
                 "}",
                 "}",
                 "]");
BSON_APPEND_INT64 (&opts, "maxAwaitTimeMS", 60*60 * 1000);

stream = mongoc_collection_watch (ctx->m_Collection, pipeline, &opts);

标签: mongodbbsonmongo-c-driver

解决方案


推荐阅读