在MongoDB中生成_id与ObjectId自动生成 [英] Generation of _id vs. ObjectId autogeneration in MongoDB

查看:2692
本文介绍了在MongoDB中生成_id与ObjectId自动生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个创建永久链接的应用程序。我不知道如何将文档保存在MondoDB中。两个策略:

I'm developing an application that create permalinks. I'm not sure how save the documents in MondoDB. Two strategies:


  1. ObjectId自动生成

  1. ObjectId autogeneration

MongoDB自动生成 _id 。我需要在永久链接字段上创建一个索引,因为我通过固定链接获取信息。此外,我可以访问ObjectId的创建时间,使用 getTimestamp()方法,所以 datetime 字段似乎是多余的,但如果我删除此字段,我需要两次调用MongoDB一个来获取信息,另一个调用时间戳。

MongoDB autogenerates the _id. I need to create an index on the permalink field because I get the information by the permalink. Also I can access to the creation time of the ObjectId, using the getTimestamp() method, so datetime fields seems to be redundant but if I delete this field I need two calls to MongoDB one to take the information and another to take the timestamp.

{
  "_id": ObjectId("5210a64f846cb004b5000001"),
  "permalink": "ca8W7mc0ZUx43bxTuSGN",
  "data": "a lot of stuff",
  "datetime": ISODate("2013-08-18T11:47:43.460+-100")
}


<生成_id

  • Generate _id

    我用固定链接生成 _id

    {
      "_id": "ca8W7mc0ZUx43bxTuSGN",
      "data": "a lot of stuff",
      "datetime": ISODate("2013-08-18T11:47:43.460+-100")
    }
    


  • 我没有看到使用ObjectIds的任何优势。我错过了什么吗?

    I not see any advantage to use ObjectIds. Am I missing something?

    推荐答案

    ObjectId 您没有一个集合中的每个文档的唯一键。它们是独一无二的,所以您不必担心冲突,并且在大型部署中不会太大的担心(他们有利弊,更多地阅读更多这里)。

    ObjectIds are there for situations where you don't have a unique key for every document in a collection. They're unique, so you don't have to worry about conflicts and they shard reasonably well in large deployments without too much worry (they have they're pros and cons, read more here).

    ObjectId 还包含客户端的时间戳,其中 ObjectId (除非DB服务器配置为生成所有密钥)。这样,您注意到,您可以使用时间戳来执行某些日期操作。但是,如果您计划使用聚合框架,您将发现您目前无法在任何日期操作中使用 ObjectId issues )。如果要使用AF,您需要一个包含日期的第二个字段,不幸的是双重存储它与 ObjectId 的内部值。

    The ObjectId also contains the timestamp of the client where the ObjectId was generated (unless the DB server is configured to generate all keys). With that, as you noticed, you can use the time stamp to perform some date operations. However, if you plan on using the Aggregation Framework, you'll find that you can't use an ObjectId in any date operations currently (issue). If you want to use the AF, you'll need a second field that contains the date, unfortunately doubly storing it with the ObjectId's internal value.

    如果您放心,您生成的 _id 是唯一的,那么使用 ObjectId 在您的数据结构。

    If you can be assured that the _id you're generating is unique, then there's not much reason to use an ObjectId in your data structure.

    这篇关于在MongoDB中生成_id与ObjectId自动生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆