Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - MongoDB trying to marge two tables by id - cant make this

I have two tables in my database.

teams table:

[
  {
    "users": [
      { "id": '5f9971e6f4f60959c0668896', "role": 'admin' },
      { "id": '5fb11570ece5672ba95850ee', "role": 'read' }
    ],
    "_id": '5fb0f993795d1634d4e486dc',
    "name": 'team1'
  },
  {
    "users": [
      { "id": '5fb11570ece5672ba95850ee', "role": 'admin' }
    ],
    "_id": "5fb0f993795d1634d4e48fed",
    "name": 'team2'
   }
]

users table:

[
 {
  "_id" : ObjectId("5f9971e6f4f60959c0668896"),
    "firstname" : "foo",
    "lastname" : "bar"
  },
  {
  "_id" : ObjectId("5fb11570ece5672ba95850ee"),
    "firstname" : "hey",
    "lastname" : "you"
  },
  {
  "_id" : ObjectId("5fb11570ece5672ba95grs0"),
    "firstname" : "12",
    "lastname" : "34"
  }
]

and what i want to get is this:

{
 users: 
  [
    { id: '5f9971e6f4f60959c0668896',firstname: "foo",lastname: "bar", role: 'admin' },
    { id: '5fb11570ece5672ba95850ee',firstname: "hey",lastname: "you", role: 'read' }
  ],
  _id: 5fb0f993795d1634d4e486dc,
  name: 'team1'
}

i'm trying to solve this a week and i didn't find solution.

Teams.aggregate([
            {
              $lookup: {
                from: "users",
                localField: "_id",
                foreignField: "users.id",
                as: "users",
              },
            },
          ]).then((data) => {
            console.log("data", data);
          });

tnx for the help

question from:https://stackoverflow.com/questions/65883359/mongodb-trying-to-marge-two-tables-by-id-cant-make-this

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

Please log in or register to reply this article.

...