是否可以在 MongoDB 中配置 ObjectId 默认字段名称?

发布于 2025-01-04 01:46:10 字数 171 浏览 1 评论 0原文

是否可以将 ObjectId 字段名称从“_id”更改为“id”或其他名称?

我一直在查看文档,到目前为止还没有发现任何与此相关的内容。 我在服务器上使用 MongoDB 和 pymongo(python 驱动程序),我将在服务器上提供 JSON 对象,而我在客户端上使用的 js 库需要带有“id”字段的对象。

Is it possible to change the ObjectId field name from '_id' to 'id', or something else?

I've been looking in the docs and so far haven't found anything concerning this.
I'm using MongoDB with pymongo (python driver) on the server, where I'll provide JSON objects, and the js library I'm using on the client expects objects with an 'id' field.

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

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

发布评论

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

评论(2

韶华倾负 2025-01-11 01:46:10

数据库总是期望或添加一个“_id”字段,但在某些情况下您实际上可以从客户端屏蔽此字段。

查看参考 href="http://api.mongodb.org/python/current/api/pymongo/database.html#pymongo.database.Database.add_son_manipulator" rel="nofollow">SON 操纵器。您可以在插入文档和提取文档时对其进行转换,以动态更改“_id”字段,使其看起来像“id”字段一样。但请注意,这只会转换文档 - 而不是查询: findOne({"id": "1234567890"}) 不会找到任何内容,因为数据库中并不真正存在“id”字段。

您必须自己决定这对于您的用例是否是个好主意。

The database will always expect or add an "_id" field, but you can actually mask this from the client in some cases.

Check out the references on SON manipulators. You can transform documents as you insert them and extract them to dynamically change the "_id" field to appear as if it is an "id" field. Be warned, however, that this will only transform the document - NOT the queries: findOne({"id": "1234567890"}) won't find anything because the "id" field doesn't really exist in the database.

You will have to decide for yourself whether this is a good idea for your use case.

暮色兮凉城 2025-01-11 01:46:10

我不这么认为。 _id 字段是为每个创建的文档自动创建的。如果您想使用其他值(例如整数值),您可以创建不同的 id 字段。

I don't think so. The _id field is created automatically for every document created. You could create a different id field if you wanted to use something else like an integer value.

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