mongodb:通过子字符串查询objectid

发布于 2025-02-05 18:34:12 字数 168 浏览 5 评论 0原文

我希望能够通过我的MongoDB集合中的子字段查询_id字段。但是,由于objectid是它自己的对象,而不是纯字符串,因此很难。这是我目前无济于事的查询,但希望它可以更加清楚我要完成的工作。

{_id: {$regex: '62a0ed7'}}

非常感谢!

I want to be able to query the _id field via a substring in my MongoDB collection. However since the ObjectId is it's own object and not a pure string this is difficult. This is the Query I'm currently using to no avail, but hopefully it gives more clarity on what I'm trying to accomplish.

{_id: {$regex: '62a0ed7'}}

Many thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如何视而不见 2025-02-12 18:34:15

你不能
REGEX表达式查询运算符对包含Objectid的字段。

我建议提供自己的唯一字符串作为 _id ,然后您可以使用 Regex
查询的表达。

示例:

    // This will add a tempUserId property to each document
    Model.aggregate([
      {
        $addFields: {
          tempUserId: { $toString: '$_id' },
        }
      },
      {
        $match: {
          tempUserId: { $regex: '62a0ed7', $options: "i" }
        }
      }
    ]);

一个更快的解决方案是您还可以添加一个pre create钩子或其他任何东西来保存ID(_id除外),该iD包含objectid(_id)作为字符串,并且可以在其上进行文本索引并执行搜索而不是正则。

You can not
query with a regex expression operator against a field that contains ObjectId's.

I suggest providing your own unique string as _id then you can use a regex
the expression for querying.

Example:

    // This will add a tempUserId property to each document
    Model.aggregate([
      {
        $addFields: {
          tempUserId: { $toString: '$_id' },
        }
      },
      {
        $match: {
          tempUserId: { $regex: '62a0ed7', $options: "i" }
        }
      }
    ]);

A faster solution is that you can also add a pre create hook or whatever to save an id (other than the _id) containing the value of the ObjectId (_id) as a string and you can make a text index on it and do search instead of regex.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文