Mongodb加入从String到ObjectId的_id字段 [英] Mongodb Join on _id field from String to ObjectId

查看:23
本文介绍了Mongodb加入从String到ObjectId的_id字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个收藏

  1. 用户

{
   "_id" : ObjectId("584aac38686860d502929b8b"),
   "name" : "John"
}

  • 角色

  • Role

    {
       "_id" : ObjectId("584aaca6686860d502929b8d"),
       "role" : "Admin",
       "userId" : "584aac38686860d502929b8b"  
    }
    

  • 我想根据 userId(在 role 集合中)- _id(在 user 中加入这些集合> 收藏).

    I want to join these collection based on the userId (in role collection) - _id ( in user collection).

    我尝试了以下查询:

    db.role.aggregate({
      "$lookup": {
        "from": "user",
        "localField": "userId",
        "foreignField": "_id",
        "as": "output"
      }
    })
    

    只要我将 userId 存储为 ObjectId,这就会给我预期的结果.当我的 userId 是字符串时,没有结果.ps:我试过了

    This gives me expected results as long as i store userId as a ObjectId. When my userId is a string there are no results. Ps: I tried

    foreignField: '_id'.valueOf()

    foreignField: '_id'.valueOf()

    foreignField: '_id'.toString()

    foreignField: '_id'.toString()

    .但是根据 ObjectId 字符串字段匹配/加入没有运气.

    . But no luck to match/join based on a ObjectId-string fields.

    任何帮助将不胜感激.

    推荐答案

    这在 MongoDB 3.4 中是不可能的.此功能已被请求,但尚未实施.以下是相应的门票:

    This is not possible as of MongoDB 3.4. This feature has already been requested, but hasn't been implemented yet. Here are the corresponding tickets:

    现在您必须将 userId 存储为 ObjectId

    For now you'll have to store userId as ObjectId

    编辑

    以前的票证在 MongoDB 4.0 中已修复.您现在可以使用以下查询实现此目的:

    The previous tickets were fixed in MongoDB 4.0. You can now achieve this with the folowing query:

    db.user.aggregate([
      {
        "$project": {
          "_id": {
            "$toString": "$_id"
          }
        }
      },
      {
        "$lookup": {
          "from": "role",
          "localField": "_id",
          "foreignField": "userId",
          "as": "role"
        }
      }
    ])
    

    结果:

    [
      {
        "_id": "584aac38686860d502929b8b",
        "role": [
          {
            "_id": ObjectId("584aaca6686860d502929b8d"),
            "role": "Admin",
            "userId": "584aac38686860d502929b8b"
          }
        ]
      }
    ]
    

    在线试用:mongoplayground.net/p/JoLPVIb1OLS

    这篇关于Mongodb加入从String到ObjectId的_id字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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