Mongo Join with specific columns












0















This question is in reference to this stack question.



I am trying to join the user data to user type and join that with loans which is joined with loan type. How do I achieve this?



I have the following data set.



db={

loans:[
{
loanId : ObjectId("123123123123"),
loanAmount: 1000,
loanType : 1,
userId: 12
} ,{
loanId : ObjectId("123123123123"),
loanAmount: 300,
loanType : 2,
userId: 12
}
],
loanType:[
{_id:ObjectId("12312312"),
loanTypeId : 1,
type : "Home Loan"
},{_id:ObjectId("12312313"),
loanTypeId : 2,
type : "Bike Loan"
}
],
User: [
{
_id: ObjectId("59a504eb6171b554c02292a9"),
"userName": "Shahabaz Shafi",
"dateOfBirth": "1992-01-01",
userId: 12,
userType: 1,
"addres": {
"country": "India",
"state": "Karnataka",
"city": "Bengaluru"
}
}
],
UserType:[
{_id:ObjectId("1233212334"),userTypeId:1, type:'student'},
{_id:ObjectId("1233212334"),userTypeId:1, type:'staff' }
]
}


Expecting this flat output from the above dataset



Output :



{
_id: ObjectId("59a504eb6171b554c02292a9"),
"userName": "Shahabaz Shafi",
"dateOfBirth": "1992-01-01",
userId: 12,
userType: 1,
userTypeName : 'student',

"addres": {
"country": "India",
"state": "Karnataka",
"city": "Bengaluru"
}

loans : [
{
loanId : ObjectId("123123123123"),
loanAmount: 1000,
loanType : 1,
type : "Home Loan",
userId: 12,
} ,{
loanId : ObjectId("123123123123"),
loanAmount: 300,
loanType : 2,
type : "Bike Loan",
userId: 12
}

]
}


I tried $lookup but it creates a separate array rather than one array.










share|improve this question





























    0















    This question is in reference to this stack question.



    I am trying to join the user data to user type and join that with loans which is joined with loan type. How do I achieve this?



    I have the following data set.



    db={

    loans:[
    {
    loanId : ObjectId("123123123123"),
    loanAmount: 1000,
    loanType : 1,
    userId: 12
    } ,{
    loanId : ObjectId("123123123123"),
    loanAmount: 300,
    loanType : 2,
    userId: 12
    }
    ],
    loanType:[
    {_id:ObjectId("12312312"),
    loanTypeId : 1,
    type : "Home Loan"
    },{_id:ObjectId("12312313"),
    loanTypeId : 2,
    type : "Bike Loan"
    }
    ],
    User: [
    {
    _id: ObjectId("59a504eb6171b554c02292a9"),
    "userName": "Shahabaz Shafi",
    "dateOfBirth": "1992-01-01",
    userId: 12,
    userType: 1,
    "addres": {
    "country": "India",
    "state": "Karnataka",
    "city": "Bengaluru"
    }
    }
    ],
    UserType:[
    {_id:ObjectId("1233212334"),userTypeId:1, type:'student'},
    {_id:ObjectId("1233212334"),userTypeId:1, type:'staff' }
    ]
    }


    Expecting this flat output from the above dataset



    Output :



    {
    _id: ObjectId("59a504eb6171b554c02292a9"),
    "userName": "Shahabaz Shafi",
    "dateOfBirth": "1992-01-01",
    userId: 12,
    userType: 1,
    userTypeName : 'student',

    "addres": {
    "country": "India",
    "state": "Karnataka",
    "city": "Bengaluru"
    }

    loans : [
    {
    loanId : ObjectId("123123123123"),
    loanAmount: 1000,
    loanType : 1,
    type : "Home Loan",
    userId: 12,
    } ,{
    loanId : ObjectId("123123123123"),
    loanAmount: 300,
    loanType : 2,
    type : "Bike Loan",
    userId: 12
    }

    ]
    }


    I tried $lookup but it creates a separate array rather than one array.










    share|improve this question



























      0












      0








      0








      This question is in reference to this stack question.



      I am trying to join the user data to user type and join that with loans which is joined with loan type. How do I achieve this?



      I have the following data set.



      db={

      loans:[
      {
      loanId : ObjectId("123123123123"),
      loanAmount: 1000,
      loanType : 1,
      userId: 12
      } ,{
      loanId : ObjectId("123123123123"),
      loanAmount: 300,
      loanType : 2,
      userId: 12
      }
      ],
      loanType:[
      {_id:ObjectId("12312312"),
      loanTypeId : 1,
      type : "Home Loan"
      },{_id:ObjectId("12312313"),
      loanTypeId : 2,
      type : "Bike Loan"
      }
      ],
      User: [
      {
      _id: ObjectId("59a504eb6171b554c02292a9"),
      "userName": "Shahabaz Shafi",
      "dateOfBirth": "1992-01-01",
      userId: 12,
      userType: 1,
      "addres": {
      "country": "India",
      "state": "Karnataka",
      "city": "Bengaluru"
      }
      }
      ],
      UserType:[
      {_id:ObjectId("1233212334"),userTypeId:1, type:'student'},
      {_id:ObjectId("1233212334"),userTypeId:1, type:'staff' }
      ]
      }


      Expecting this flat output from the above dataset



      Output :



      {
      _id: ObjectId("59a504eb6171b554c02292a9"),
      "userName": "Shahabaz Shafi",
      "dateOfBirth": "1992-01-01",
      userId: 12,
      userType: 1,
      userTypeName : 'student',

      "addres": {
      "country": "India",
      "state": "Karnataka",
      "city": "Bengaluru"
      }

      loans : [
      {
      loanId : ObjectId("123123123123"),
      loanAmount: 1000,
      loanType : 1,
      type : "Home Loan",
      userId: 12,
      } ,{
      loanId : ObjectId("123123123123"),
      loanAmount: 300,
      loanType : 2,
      type : "Bike Loan",
      userId: 12
      }

      ]
      }


      I tried $lookup but it creates a separate array rather than one array.










      share|improve this question
















      This question is in reference to this stack question.



      I am trying to join the user data to user type and join that with loans which is joined with loan type. How do I achieve this?



      I have the following data set.



      db={

      loans:[
      {
      loanId : ObjectId("123123123123"),
      loanAmount: 1000,
      loanType : 1,
      userId: 12
      } ,{
      loanId : ObjectId("123123123123"),
      loanAmount: 300,
      loanType : 2,
      userId: 12
      }
      ],
      loanType:[
      {_id:ObjectId("12312312"),
      loanTypeId : 1,
      type : "Home Loan"
      },{_id:ObjectId("12312313"),
      loanTypeId : 2,
      type : "Bike Loan"
      }
      ],
      User: [
      {
      _id: ObjectId("59a504eb6171b554c02292a9"),
      "userName": "Shahabaz Shafi",
      "dateOfBirth": "1992-01-01",
      userId: 12,
      userType: 1,
      "addres": {
      "country": "India",
      "state": "Karnataka",
      "city": "Bengaluru"
      }
      }
      ],
      UserType:[
      {_id:ObjectId("1233212334"),userTypeId:1, type:'student'},
      {_id:ObjectId("1233212334"),userTypeId:1, type:'staff' }
      ]
      }


      Expecting this flat output from the above dataset



      Output :



      {
      _id: ObjectId("59a504eb6171b554c02292a9"),
      "userName": "Shahabaz Shafi",
      "dateOfBirth": "1992-01-01",
      userId: 12,
      userType: 1,
      userTypeName : 'student',

      "addres": {
      "country": "India",
      "state": "Karnataka",
      "city": "Bengaluru"
      }

      loans : [
      {
      loanId : ObjectId("123123123123"),
      loanAmount: 1000,
      loanType : 1,
      type : "Home Loan",
      userId: 12,
      } ,{
      loanId : ObjectId("123123123123"),
      loanAmount: 300,
      loanType : 2,
      type : "Bike Loan",
      userId: 12
      }

      ]
      }


      I tried $lookup but it creates a separate array rather than one array.







      mongodb mongodb-query aggregation-framework






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 15 '18 at 16:58









      Anthony Winzlet

      17.4k42045




      17.4k42045










      asked Nov 15 '18 at 16:55









      ShahabazShahabaz

      981211




      981211
























          1 Answer
          1






          active

          oldest

          votes


















          1














             /* Collection 1 : users */

          {
          "_id" : ObjectId("5c46eaf2e166363e18d6ef91"),
          "userName" : "Shahabaz Shafi",
          "dateOfBirth" : "1992-01-01",
          "userId" : 12,
          "userType" : 1,
          "addres" : {
          "country" : "India",
          "state" : "Karnataka",
          "city" : "Bengaluru"
          }
          }

          /* Collection 2 : userTypes */
          /* 1 */
          {
          "_id" : ObjectId("5c46eb46e166363e18d6ef92"),
          "userTypeId" : 1,
          "type" : "student"
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46eb46e166363e18d6ef93"),
          "userTypeId" : 2,
          "type" : "staff"
          }

          /* Collection 3 : loans */
          /* 1 */
          {
          "_id" : ObjectId("5c46eb8be166363e18d6ef94"),
          "loanAmount" : 1000,
          "loanType" : 1,
          "userId" : 12
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46eb8be166363e18d6ef95"),
          "loanAmount" : 300,
          "loanType" : 2,
          "userId" : 12
          }

          /* Collection 4 : loanType */
          /* 1 */
          {
          "_id" : ObjectId("5c46ebc1e166363e18d6ef96"),
          "loanTypeId" : 1,
          "type" : "Home Loan"
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46ebc1e166363e18d6ef97"),
          "loanTypeId" : 2,
          "type" : "Bike Loan"
          }

          Solution:

          db.users.aggregate([
          {
          // Join collections users and usertypes
          $lookup : {
          from: "userTypes",
          localField: "userType",
          foreignField: "userTypeId",
          as: "userTypes"
          }
          },
          {
          // Merge keys of array of objects userTypes in existing document
          $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$userTypes", 0 ] }, "$$ROOT" ] } }
          },
          {
          // Remove keys userTypes and userTypeId
          $project : {
          "userTypes": 0,
          "userTypeId" : 0
          }
          },
          {
          // Join current document obtained with loans collection
          $lookup : {
          from: "loans",
          localField: "userId",
          foreignField: "userId",
          as: "loans"
          }
          },
          {
          // Break array obtained from loans into separate documents
          $unwind : "$loans"
          },
          {
          // Join current documents obtained with loanType collection
          $lookup : {
          from: "loanType",
          localField: "loans.loanType",
          foreignField: "loanTypeId",
          as: "loanTypes"
          }
          },
          {
          // Break array obtained from loans into separate documents
          $unwind: "$loanTypes"
          },
          {
          // Display fields as per requirement and modify fields accordingly
          $project : {
          _id:"$_id",
          "type" :1,
          "userName" : 1,
          "dateOfBirth" : 1,
          "userId" : 1,
          "userType" : 1,
          "addres" : 1,
          "loanAmount" : "$loans.loanAmount",
          "loantype": "$loans.loanType",
          "loanTypeName" : "$loanTypes.type",
          "loanId" : "$loans._id"

          }
          },
          {
          // Merge documents based on condition given and push data in loans array as per output required
          $group:{
          _id : "$_id",
          "type" : {"$first" :"$type" },
          "userName" : {"$first" :"$userName" },
          "dateOfBirth" : {"$first" :"$dateOfBirth" },
          "userId" : {"$first" :"$userId" },
          "userType" : {"$first" :"$userType" },
          "addres" : {"$first" :"$addres" },
          "loans":{
          $push:{
          "loanAmount" : "$loanAmount",
          "loanType" : "$loantype",
          "type" : "$loanTypeName",
          "loanId" : "$loanId"
          }
          }
          }
          }
          ]);

          Output:

          /* 1 */
          {
          "_id" : ObjectId("5c46eaf2e166363e18d6ef91"),
          "type" : "student",
          "userName" : "Shahabaz Shafi",
          "dateOfBirth" : "1992-01-01",
          "userId" : 12,
          "userType" : 1,
          "addres" : {
          "country" : "India",
          "state" : "Karnataka",
          "city" : "Bengaluru"
          },
          "loans" : [
          {
          "loanAmount" : 1000,
          "loanType" : 1,
          "type" : "Home Loan",
          "loanId" : ObjectId("5c46eb8be166363e18d6ef94")
          },
          {
          "loanAmount" : 300,
          "loanType" : 2,
          "type" : "Bike Loan",
          "loanId" : ObjectId("5c46eb8be166363e18d6ef95")
          }
          ]
          }

          @Anthony Winzlet @Shahabaz Please try this.





          share|improve this answer





















          • 1





            Please add an explanation to your code.

            – Arpit Svt
            Jan 22 at 12:43











          • @Arpit Svt I had added comments to my code. Please try using the sample collections posted in the code.

            – anr241193
            Jan 24 at 4:58











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53324383%2fmongo-join-with-specific-columns%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














             /* Collection 1 : users */

          {
          "_id" : ObjectId("5c46eaf2e166363e18d6ef91"),
          "userName" : "Shahabaz Shafi",
          "dateOfBirth" : "1992-01-01",
          "userId" : 12,
          "userType" : 1,
          "addres" : {
          "country" : "India",
          "state" : "Karnataka",
          "city" : "Bengaluru"
          }
          }

          /* Collection 2 : userTypes */
          /* 1 */
          {
          "_id" : ObjectId("5c46eb46e166363e18d6ef92"),
          "userTypeId" : 1,
          "type" : "student"
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46eb46e166363e18d6ef93"),
          "userTypeId" : 2,
          "type" : "staff"
          }

          /* Collection 3 : loans */
          /* 1 */
          {
          "_id" : ObjectId("5c46eb8be166363e18d6ef94"),
          "loanAmount" : 1000,
          "loanType" : 1,
          "userId" : 12
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46eb8be166363e18d6ef95"),
          "loanAmount" : 300,
          "loanType" : 2,
          "userId" : 12
          }

          /* Collection 4 : loanType */
          /* 1 */
          {
          "_id" : ObjectId("5c46ebc1e166363e18d6ef96"),
          "loanTypeId" : 1,
          "type" : "Home Loan"
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46ebc1e166363e18d6ef97"),
          "loanTypeId" : 2,
          "type" : "Bike Loan"
          }

          Solution:

          db.users.aggregate([
          {
          // Join collections users and usertypes
          $lookup : {
          from: "userTypes",
          localField: "userType",
          foreignField: "userTypeId",
          as: "userTypes"
          }
          },
          {
          // Merge keys of array of objects userTypes in existing document
          $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$userTypes", 0 ] }, "$$ROOT" ] } }
          },
          {
          // Remove keys userTypes and userTypeId
          $project : {
          "userTypes": 0,
          "userTypeId" : 0
          }
          },
          {
          // Join current document obtained with loans collection
          $lookup : {
          from: "loans",
          localField: "userId",
          foreignField: "userId",
          as: "loans"
          }
          },
          {
          // Break array obtained from loans into separate documents
          $unwind : "$loans"
          },
          {
          // Join current documents obtained with loanType collection
          $lookup : {
          from: "loanType",
          localField: "loans.loanType",
          foreignField: "loanTypeId",
          as: "loanTypes"
          }
          },
          {
          // Break array obtained from loans into separate documents
          $unwind: "$loanTypes"
          },
          {
          // Display fields as per requirement and modify fields accordingly
          $project : {
          _id:"$_id",
          "type" :1,
          "userName" : 1,
          "dateOfBirth" : 1,
          "userId" : 1,
          "userType" : 1,
          "addres" : 1,
          "loanAmount" : "$loans.loanAmount",
          "loantype": "$loans.loanType",
          "loanTypeName" : "$loanTypes.type",
          "loanId" : "$loans._id"

          }
          },
          {
          // Merge documents based on condition given and push data in loans array as per output required
          $group:{
          _id : "$_id",
          "type" : {"$first" :"$type" },
          "userName" : {"$first" :"$userName" },
          "dateOfBirth" : {"$first" :"$dateOfBirth" },
          "userId" : {"$first" :"$userId" },
          "userType" : {"$first" :"$userType" },
          "addres" : {"$first" :"$addres" },
          "loans":{
          $push:{
          "loanAmount" : "$loanAmount",
          "loanType" : "$loantype",
          "type" : "$loanTypeName",
          "loanId" : "$loanId"
          }
          }
          }
          }
          ]);

          Output:

          /* 1 */
          {
          "_id" : ObjectId("5c46eaf2e166363e18d6ef91"),
          "type" : "student",
          "userName" : "Shahabaz Shafi",
          "dateOfBirth" : "1992-01-01",
          "userId" : 12,
          "userType" : 1,
          "addres" : {
          "country" : "India",
          "state" : "Karnataka",
          "city" : "Bengaluru"
          },
          "loans" : [
          {
          "loanAmount" : 1000,
          "loanType" : 1,
          "type" : "Home Loan",
          "loanId" : ObjectId("5c46eb8be166363e18d6ef94")
          },
          {
          "loanAmount" : 300,
          "loanType" : 2,
          "type" : "Bike Loan",
          "loanId" : ObjectId("5c46eb8be166363e18d6ef95")
          }
          ]
          }

          @Anthony Winzlet @Shahabaz Please try this.





          share|improve this answer





















          • 1





            Please add an explanation to your code.

            – Arpit Svt
            Jan 22 at 12:43











          • @Arpit Svt I had added comments to my code. Please try using the sample collections posted in the code.

            – anr241193
            Jan 24 at 4:58
















          1














             /* Collection 1 : users */

          {
          "_id" : ObjectId("5c46eaf2e166363e18d6ef91"),
          "userName" : "Shahabaz Shafi",
          "dateOfBirth" : "1992-01-01",
          "userId" : 12,
          "userType" : 1,
          "addres" : {
          "country" : "India",
          "state" : "Karnataka",
          "city" : "Bengaluru"
          }
          }

          /* Collection 2 : userTypes */
          /* 1 */
          {
          "_id" : ObjectId("5c46eb46e166363e18d6ef92"),
          "userTypeId" : 1,
          "type" : "student"
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46eb46e166363e18d6ef93"),
          "userTypeId" : 2,
          "type" : "staff"
          }

          /* Collection 3 : loans */
          /* 1 */
          {
          "_id" : ObjectId("5c46eb8be166363e18d6ef94"),
          "loanAmount" : 1000,
          "loanType" : 1,
          "userId" : 12
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46eb8be166363e18d6ef95"),
          "loanAmount" : 300,
          "loanType" : 2,
          "userId" : 12
          }

          /* Collection 4 : loanType */
          /* 1 */
          {
          "_id" : ObjectId("5c46ebc1e166363e18d6ef96"),
          "loanTypeId" : 1,
          "type" : "Home Loan"
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46ebc1e166363e18d6ef97"),
          "loanTypeId" : 2,
          "type" : "Bike Loan"
          }

          Solution:

          db.users.aggregate([
          {
          // Join collections users and usertypes
          $lookup : {
          from: "userTypes",
          localField: "userType",
          foreignField: "userTypeId",
          as: "userTypes"
          }
          },
          {
          // Merge keys of array of objects userTypes in existing document
          $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$userTypes", 0 ] }, "$$ROOT" ] } }
          },
          {
          // Remove keys userTypes and userTypeId
          $project : {
          "userTypes": 0,
          "userTypeId" : 0
          }
          },
          {
          // Join current document obtained with loans collection
          $lookup : {
          from: "loans",
          localField: "userId",
          foreignField: "userId",
          as: "loans"
          }
          },
          {
          // Break array obtained from loans into separate documents
          $unwind : "$loans"
          },
          {
          // Join current documents obtained with loanType collection
          $lookup : {
          from: "loanType",
          localField: "loans.loanType",
          foreignField: "loanTypeId",
          as: "loanTypes"
          }
          },
          {
          // Break array obtained from loans into separate documents
          $unwind: "$loanTypes"
          },
          {
          // Display fields as per requirement and modify fields accordingly
          $project : {
          _id:"$_id",
          "type" :1,
          "userName" : 1,
          "dateOfBirth" : 1,
          "userId" : 1,
          "userType" : 1,
          "addres" : 1,
          "loanAmount" : "$loans.loanAmount",
          "loantype": "$loans.loanType",
          "loanTypeName" : "$loanTypes.type",
          "loanId" : "$loans._id"

          }
          },
          {
          // Merge documents based on condition given and push data in loans array as per output required
          $group:{
          _id : "$_id",
          "type" : {"$first" :"$type" },
          "userName" : {"$first" :"$userName" },
          "dateOfBirth" : {"$first" :"$dateOfBirth" },
          "userId" : {"$first" :"$userId" },
          "userType" : {"$first" :"$userType" },
          "addres" : {"$first" :"$addres" },
          "loans":{
          $push:{
          "loanAmount" : "$loanAmount",
          "loanType" : "$loantype",
          "type" : "$loanTypeName",
          "loanId" : "$loanId"
          }
          }
          }
          }
          ]);

          Output:

          /* 1 */
          {
          "_id" : ObjectId("5c46eaf2e166363e18d6ef91"),
          "type" : "student",
          "userName" : "Shahabaz Shafi",
          "dateOfBirth" : "1992-01-01",
          "userId" : 12,
          "userType" : 1,
          "addres" : {
          "country" : "India",
          "state" : "Karnataka",
          "city" : "Bengaluru"
          },
          "loans" : [
          {
          "loanAmount" : 1000,
          "loanType" : 1,
          "type" : "Home Loan",
          "loanId" : ObjectId("5c46eb8be166363e18d6ef94")
          },
          {
          "loanAmount" : 300,
          "loanType" : 2,
          "type" : "Bike Loan",
          "loanId" : ObjectId("5c46eb8be166363e18d6ef95")
          }
          ]
          }

          @Anthony Winzlet @Shahabaz Please try this.





          share|improve this answer





















          • 1





            Please add an explanation to your code.

            – Arpit Svt
            Jan 22 at 12:43











          • @Arpit Svt I had added comments to my code. Please try using the sample collections posted in the code.

            – anr241193
            Jan 24 at 4:58














          1












          1








          1







             /* Collection 1 : users */

          {
          "_id" : ObjectId("5c46eaf2e166363e18d6ef91"),
          "userName" : "Shahabaz Shafi",
          "dateOfBirth" : "1992-01-01",
          "userId" : 12,
          "userType" : 1,
          "addres" : {
          "country" : "India",
          "state" : "Karnataka",
          "city" : "Bengaluru"
          }
          }

          /* Collection 2 : userTypes */
          /* 1 */
          {
          "_id" : ObjectId("5c46eb46e166363e18d6ef92"),
          "userTypeId" : 1,
          "type" : "student"
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46eb46e166363e18d6ef93"),
          "userTypeId" : 2,
          "type" : "staff"
          }

          /* Collection 3 : loans */
          /* 1 */
          {
          "_id" : ObjectId("5c46eb8be166363e18d6ef94"),
          "loanAmount" : 1000,
          "loanType" : 1,
          "userId" : 12
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46eb8be166363e18d6ef95"),
          "loanAmount" : 300,
          "loanType" : 2,
          "userId" : 12
          }

          /* Collection 4 : loanType */
          /* 1 */
          {
          "_id" : ObjectId("5c46ebc1e166363e18d6ef96"),
          "loanTypeId" : 1,
          "type" : "Home Loan"
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46ebc1e166363e18d6ef97"),
          "loanTypeId" : 2,
          "type" : "Bike Loan"
          }

          Solution:

          db.users.aggregate([
          {
          // Join collections users and usertypes
          $lookup : {
          from: "userTypes",
          localField: "userType",
          foreignField: "userTypeId",
          as: "userTypes"
          }
          },
          {
          // Merge keys of array of objects userTypes in existing document
          $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$userTypes", 0 ] }, "$$ROOT" ] } }
          },
          {
          // Remove keys userTypes and userTypeId
          $project : {
          "userTypes": 0,
          "userTypeId" : 0
          }
          },
          {
          // Join current document obtained with loans collection
          $lookup : {
          from: "loans",
          localField: "userId",
          foreignField: "userId",
          as: "loans"
          }
          },
          {
          // Break array obtained from loans into separate documents
          $unwind : "$loans"
          },
          {
          // Join current documents obtained with loanType collection
          $lookup : {
          from: "loanType",
          localField: "loans.loanType",
          foreignField: "loanTypeId",
          as: "loanTypes"
          }
          },
          {
          // Break array obtained from loans into separate documents
          $unwind: "$loanTypes"
          },
          {
          // Display fields as per requirement and modify fields accordingly
          $project : {
          _id:"$_id",
          "type" :1,
          "userName" : 1,
          "dateOfBirth" : 1,
          "userId" : 1,
          "userType" : 1,
          "addres" : 1,
          "loanAmount" : "$loans.loanAmount",
          "loantype": "$loans.loanType",
          "loanTypeName" : "$loanTypes.type",
          "loanId" : "$loans._id"

          }
          },
          {
          // Merge documents based on condition given and push data in loans array as per output required
          $group:{
          _id : "$_id",
          "type" : {"$first" :"$type" },
          "userName" : {"$first" :"$userName" },
          "dateOfBirth" : {"$first" :"$dateOfBirth" },
          "userId" : {"$first" :"$userId" },
          "userType" : {"$first" :"$userType" },
          "addres" : {"$first" :"$addres" },
          "loans":{
          $push:{
          "loanAmount" : "$loanAmount",
          "loanType" : "$loantype",
          "type" : "$loanTypeName",
          "loanId" : "$loanId"
          }
          }
          }
          }
          ]);

          Output:

          /* 1 */
          {
          "_id" : ObjectId("5c46eaf2e166363e18d6ef91"),
          "type" : "student",
          "userName" : "Shahabaz Shafi",
          "dateOfBirth" : "1992-01-01",
          "userId" : 12,
          "userType" : 1,
          "addres" : {
          "country" : "India",
          "state" : "Karnataka",
          "city" : "Bengaluru"
          },
          "loans" : [
          {
          "loanAmount" : 1000,
          "loanType" : 1,
          "type" : "Home Loan",
          "loanId" : ObjectId("5c46eb8be166363e18d6ef94")
          },
          {
          "loanAmount" : 300,
          "loanType" : 2,
          "type" : "Bike Loan",
          "loanId" : ObjectId("5c46eb8be166363e18d6ef95")
          }
          ]
          }

          @Anthony Winzlet @Shahabaz Please try this.





          share|improve this answer















             /* Collection 1 : users */

          {
          "_id" : ObjectId("5c46eaf2e166363e18d6ef91"),
          "userName" : "Shahabaz Shafi",
          "dateOfBirth" : "1992-01-01",
          "userId" : 12,
          "userType" : 1,
          "addres" : {
          "country" : "India",
          "state" : "Karnataka",
          "city" : "Bengaluru"
          }
          }

          /* Collection 2 : userTypes */
          /* 1 */
          {
          "_id" : ObjectId("5c46eb46e166363e18d6ef92"),
          "userTypeId" : 1,
          "type" : "student"
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46eb46e166363e18d6ef93"),
          "userTypeId" : 2,
          "type" : "staff"
          }

          /* Collection 3 : loans */
          /* 1 */
          {
          "_id" : ObjectId("5c46eb8be166363e18d6ef94"),
          "loanAmount" : 1000,
          "loanType" : 1,
          "userId" : 12
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46eb8be166363e18d6ef95"),
          "loanAmount" : 300,
          "loanType" : 2,
          "userId" : 12
          }

          /* Collection 4 : loanType */
          /* 1 */
          {
          "_id" : ObjectId("5c46ebc1e166363e18d6ef96"),
          "loanTypeId" : 1,
          "type" : "Home Loan"
          }

          /* 2 */
          {
          "_id" : ObjectId("5c46ebc1e166363e18d6ef97"),
          "loanTypeId" : 2,
          "type" : "Bike Loan"
          }

          Solution:

          db.users.aggregate([
          {
          // Join collections users and usertypes
          $lookup : {
          from: "userTypes",
          localField: "userType",
          foreignField: "userTypeId",
          as: "userTypes"
          }
          },
          {
          // Merge keys of array of objects userTypes in existing document
          $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$userTypes", 0 ] }, "$$ROOT" ] } }
          },
          {
          // Remove keys userTypes and userTypeId
          $project : {
          "userTypes": 0,
          "userTypeId" : 0
          }
          },
          {
          // Join current document obtained with loans collection
          $lookup : {
          from: "loans",
          localField: "userId",
          foreignField: "userId",
          as: "loans"
          }
          },
          {
          // Break array obtained from loans into separate documents
          $unwind : "$loans"
          },
          {
          // Join current documents obtained with loanType collection
          $lookup : {
          from: "loanType",
          localField: "loans.loanType",
          foreignField: "loanTypeId",
          as: "loanTypes"
          }
          },
          {
          // Break array obtained from loans into separate documents
          $unwind: "$loanTypes"
          },
          {
          // Display fields as per requirement and modify fields accordingly
          $project : {
          _id:"$_id",
          "type" :1,
          "userName" : 1,
          "dateOfBirth" : 1,
          "userId" : 1,
          "userType" : 1,
          "addres" : 1,
          "loanAmount" : "$loans.loanAmount",
          "loantype": "$loans.loanType",
          "loanTypeName" : "$loanTypes.type",
          "loanId" : "$loans._id"

          }
          },
          {
          // Merge documents based on condition given and push data in loans array as per output required
          $group:{
          _id : "$_id",
          "type" : {"$first" :"$type" },
          "userName" : {"$first" :"$userName" },
          "dateOfBirth" : {"$first" :"$dateOfBirth" },
          "userId" : {"$first" :"$userId" },
          "userType" : {"$first" :"$userType" },
          "addres" : {"$first" :"$addres" },
          "loans":{
          $push:{
          "loanAmount" : "$loanAmount",
          "loanType" : "$loantype",
          "type" : "$loanTypeName",
          "loanId" : "$loanId"
          }
          }
          }
          }
          ]);

          Output:

          /* 1 */
          {
          "_id" : ObjectId("5c46eaf2e166363e18d6ef91"),
          "type" : "student",
          "userName" : "Shahabaz Shafi",
          "dateOfBirth" : "1992-01-01",
          "userId" : 12,
          "userType" : 1,
          "addres" : {
          "country" : "India",
          "state" : "Karnataka",
          "city" : "Bengaluru"
          },
          "loans" : [
          {
          "loanAmount" : 1000,
          "loanType" : 1,
          "type" : "Home Loan",
          "loanId" : ObjectId("5c46eb8be166363e18d6ef94")
          },
          {
          "loanAmount" : 300,
          "loanType" : 2,
          "type" : "Bike Loan",
          "loanId" : ObjectId("5c46eb8be166363e18d6ef95")
          }
          ]
          }

          @Anthony Winzlet @Shahabaz Please try this.






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 24 at 4:51

























          answered Jan 22 at 12:31









          anr241193anr241193

          515




          515








          • 1





            Please add an explanation to your code.

            – Arpit Svt
            Jan 22 at 12:43











          • @Arpit Svt I had added comments to my code. Please try using the sample collections posted in the code.

            – anr241193
            Jan 24 at 4:58














          • 1





            Please add an explanation to your code.

            – Arpit Svt
            Jan 22 at 12:43











          • @Arpit Svt I had added comments to my code. Please try using the sample collections posted in the code.

            – anr241193
            Jan 24 at 4:58








          1




          1





          Please add an explanation to your code.

          – Arpit Svt
          Jan 22 at 12:43





          Please add an explanation to your code.

          – Arpit Svt
          Jan 22 at 12:43













          @Arpit Svt I had added comments to my code. Please try using the sample collections posted in the code.

          – anr241193
          Jan 24 at 4:58





          @Arpit Svt I had added comments to my code. Please try using the sample collections posted in the code.

          – anr241193
          Jan 24 at 4:58




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53324383%2fmongo-join-with-specific-columns%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          List item for chat from Array inside array React Native

          Thiostrepton

          Caerphilly