推荐工具
› RoboMongo
推荐书目
› 50 Tips and Tricks for MongoDB Developers
Related Blogs
› Snail in a Turtleneck
ohyeahhh
V2EX  ›  MongoDB

MongoDB 中有没有什么办法能把 ObjectId 转为 Long?

  •  
  •   ohyeahhh · Jul 5, 2019 · 13315 views
    This topic created in 2685 days ago, the information mentioned may be changed or developed.

    最近在搞一个推荐的东西,但是那套推荐算法中要的数据是 userId,itemId,rating 这种,其中 userId 和 itemId 好像只能是 Long 型,但我们的库里存的都是 ObjectId,想问下有没有什么方法能转吗?

    13 replies  •  2019-11-23 09:53:29 +08:00
    Aidenboss
    Aidenboss
    Jul 5, 2019
    1
    Number.parseInt(objectId, 16)
    sujin190
    sujin190
    Jul 5, 2019
    2
    都是二进制看你怎么解码了,按 ObjectId 解码就是 ObjectId 按 Long 解码就是 Long,但是你要怎么把 12 字节的 ObjectId 放到一个 8 字节的 Long 上去
    tikazyq
    tikazyq
    Jul 5, 2019
    3
    getTimestamp
    huoru
    huoru
    Jul 5, 2019
    4
    @tikazyq getTimestamp 是不对的。ObjectId 并不等价于其中的 Timestamp
    ohyeahhh
    ohyeahhh
    OP
    Jul 5, 2019
    5
    @Aidenboss #1 如果我要再转回来呢?
    chendy
    chendy
    Jul 5, 2019
    6
    ObjectId 12 个字节
    Long 8 个字节
    感觉很难转
    ohyeahhh
    ohyeahhh
    OP
    Jul 5, 2019
    7
    @chendy #6 如果是 String 呢 因为 ObjectId 是可以转成 String 的
    chendy
    chendy
    Jul 5, 2019
    8
    @ohyeahhh String 就啥问题没有了
    itechify
    itechify
    Jul 5, 2019 via Android
    9
    userId 这种字段可以用 ObjectId 类型,你要短一点好认作为对人类友好的表示,用一个唯一 orderNo 字段然后自己定义规则即可。
    另外,非要 long 类型作为 Id 字段的话,可以参考使用雪花算法,实现全数字,但是雪花算法算出来的 ID 跟 ObjectId 是不兼容的,也就是说,有一个雪花算法算出来的 long 型 id 为 xxx,那么 new ObjectId(xxx)是会被底层检查不符合 ObjectId 的规则导致抛出异常。
    雪花算法的 ID 也很长,要短一点的话,参考美团团队的做法,搜索一下看下怎么实现吧,但是这个我没应用过。
    个人愚见
    lihongjie0209
    lihongjie0209
    Jul 5, 2019
    10
    不可能, 超过了 long 的长度了
    metrxqin
    metrxqin
    Jul 5, 2019 via Android
    11
    ObjwctId 不可能用于存储业务参数。
    ericgui
    ericgui
    Jul 6, 2019
    12
    为什么不能存成为 string
    q540374501
    q540374501
    Nov 23, 2019
    13
    node 转成 long 还要引入 biginteger 包。。不然放不下,计算不了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4747 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 01:51 · PVG 09:51 · LAX 17:51 · JFK 20:51
    ♥ Do have faith in what you're doing.