Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

node.js - MongoDB_Join Functionality

I am new to MongoDB, here I need to form a new table from different collections where it should look like this,

userId   userName    email    phone     role

Here according to userId, I need all information from different Collections.

Data:

> db.userinfo.find().pretty()
{
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "phone" : "0000000000"
}
> db.userrole.find().pretty()
{
        "_id" : ObjectId("56d82612b63f1c31cf906003"),
        "userId" : "AD",
        "role" : "admin"
}
> db.users.find().pretty()
{
        "_id" : ObjectId("5684f3c454b1fd6926c324fd"),
        "email" : "[email protected]",
        "userId" : "AD",
        "userName" : "admin"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Its a standard lookup to join. Refer $lookup

db.userinfo.aggregate([
  {
    "$lookup": {
      "from": "userrole",
      "localField": "userId",
      "foreignField": "userId",
      "as": "roleJoin"
    }
  },
  {
    "$lookup": {
      "from": "users",
      "localField": "userId",
      "foreignField": "userId",
      "as": "userJoin"
    }
  }
])

Working Mongo playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...