How to do inner joining in MongoDB?

后端 未结 4 828
醉梦人生
醉梦人生 2021-02-08 02:31

Is it possible to do SQL inner joins kind of stuff in MongoDB , well i know there is

$lookup

attribute in aggregation pipeline and

相关标签:
4条回答
  • 2021-02-08 03:01
    > show dbs
    admin   0.000GB
    config  0.000GB
    local   0.002GB
    > use local
    switched to db local
    > show collections
    startup_log
    test1
    test2
    > db.test2.aggregate([{
    ...    $lookup: {
    ...       from: "test1",
    ...       localField: "id",
    ...       foreignField: "id",
    ...       as: "aggTest"
    ...    }
    ... }])
    
    0 讨论(0)
  • 2021-02-08 03:05

    I found answer my self it was

    $unwind done the trick to me following query worked for me

        db.USER.aggregate([{
                $lookup: {
                    from: "USER_ROLE",
                    localField: "ID",
                    foreignField: "USER_ID",
                    as: "userRole"
                }
            }, {
                $unwind: {
                    path: "$userRole",
                    preserveNullAndEmptyArrays: false
                }
            }, {
                $lookup: {
                    from: "ROLE",
                    localField: "userRole.ROLE_ID",
                    foreignField: "ID",
                    as: "role"
                }
            }, {
                $unwind: {
                    path: "$role",
                    preserveNullAndEmptyArrays: false
                }
            }, {
                $match: {
                    "role.ROLE_NAME": "staff"
                }, {
                    $project: {
                        USER_NAME: 1,
                        _id: 0
                    }
                }
                ]).pretty()
    

    Anyway thanks for the answers

    0 讨论(0)
  • 2021-02-08 03:10

    As Tiramisu wrote this looks like schema issue.

    You can make a manual inner join, by removing documents where $lookup returned empty array.

    ....
    {$lookup... as myArray},
    {$match: {"myArray":{$ne:[]}}},
    {$lookup... as myArray2},
    {$match: {"myArray2":{$ne:[]}}},
    

    schema change

    I personally will go for schema update, like this:

    db.User.find({})
    {
       ID : 1,
       USER_NAME : "John",
       password : "pass"
       roles:[{ID : 1,  ROLE_NAME : "admin"}]
    }
    
    
    db.ROLE.find({})
    {
       ID : 1,
       ROLE_NAME : "admin"
    },
    
    0 讨论(0)
  • 2021-02-08 03:14

    Will this help

    const RolesSchema = new Schema({
      ....
    
    });
    const Roles = mongoose.model('Roles', RolesSchema);
    
    
    const UserSchema = new Schema({
      ...
    
      roles: [{ type: mongoose.Schema.Types.ObjectId, ref: "Roles" }]
    });
    

    using the populate on userschema you can also reduce the redundancy

    0 讨论(0)
提交回复
热议问题