将 json 字符串中的 24 个字符的十六进制值解析为 BsonObjectId

Parse 24-char hex value in json string as BsonObjectId

我正在尝试在 .NET5 Web API(rest 端点)中实现以下流程。

  1. 接收 mongodb 查询作为 json 字符串
  2. 将 json 字符串转换为 BsonDocument
  3. 使用BsonDocument查询MongoDb集合

只要我的 json 查询文档中没有 ObjectId(我猜是日期),这就很好用。

以下示例

示例 1

{
  "studentId": "5fd627c58583b9001270e94c"
}

示例 2

{
  "$or": [
      { "cityId": "5fcf975f1749910011c194f9" },
      { "regionId": "60be5a367eeac21aebefdec4" }
   ]
}

显然 studentId 是一个 ObjectId,不幸的是 BsonDocument.Parse(json);BsonSerializer.Deserialize<BsonDocument>(json); 将该 ObjectId 转换为 BsonString 而不是 BsonObjectId。

有人可以为我指明如何实现自动映射的正确方向吗?

我想正则表达式是你唯一的朋友

var json = @"
{
    $or: [
        { cityId: ""5fcf975f1749910011c194f9"" },
        { regionId: ""60be5a367eeac21aebefdec4"" }
    ]
}";

json = Regex.Replace(
    json,
    "\"[a-f\d]{24}\"",
    m => $"ObjectId({m.Value})");

BsonDocument query = BsonDocument.Parse(json);