【问题标题】:How to set _id to be 32bit Integer?如何将_id设置为32位整数?
【发布时间】:2012-11-13 06:21:37
【问题描述】:

我目前正在将数据提取到 MongoDB 中,以后需要将这些数据提取到单独的应用程序中。此应用程序要求 _id 字段为 32 位整数。

确保将结果文档中的 _id 属性显式设置为唯一的 32 位整数。 source

我正在使用 pymongo 将文档插入到集合中。

def parse_tweet(in_t):
    t = {}
    t["text"] = in_t["text"]
    t["shape"] = in_t["coordinates"]["coordinates"][0], in_t["coordinates"]["coordinates"][1]
    return t

这给了我预期的文件:

{
  "_id" : ObjectId("50a0de04f26afb14f4bba03d"),
  "text" : "hello world",
  "shape" : [144.9557834, -37.8208589],
}

如何将 _id 值显式设置为 32 位整数?
我不打算存储超过 600 万份文档。

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    只需生成一个 id 并将其传递。 Id 可以是任何东西(数组除外)。

    def parse_tweet(in_t):
        t = {}
        t["_id"] = get_me_an_int32_id
        t["text"] = in_t["text"]
        t["shape"] = in_t["coordinates"]["coordinates"][0], in_t["coordinates"]["coordinates"][1]
        return t
    

    您必须自己处理它的独特性。 MongoDB 只会确保您不存储重复值。但是你在哪里获得独特的价值 - 那是你的问题。

    这里有一些想法:How to make an Autoincrementing field。

    【讨论】:

    • pymongo 可能会以不同的方式处理这个问题(我是 PHP),因为这不在文档中:api.mongodb.org/python/current/api/index.html 但是如果您的应用程序不是,MongoDB 的默认存储不是严格的 int 32面向处理这个问题可能会中断,因此我会确保它使用 php.net/manual/en/class.mongoint32.php 的等价物,或者只是编写应用程序来处理 Mongo 的这个小方面
    • 有没有机会分享 get_me_an_int32_id 函数中的一些逻辑?我在看你的链接,但不确定最优雅的 python 计数器?
    • 一般来说,如果您可以控制应用程序,最好的方法是使用int() 函数对应用程序进行编码,以将所有从 MongoDB 收集的数字转换为安全整数,如下所示:stackoverflow.com/questions/3387655/…
    猜你喜欢
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多