0

I have a mongodb document as

{
  "_id": 10001,
  "uid": 1413430,
  "loginType": "student"
}

the _id is bookId. This book Id is primary key in "books" collection which contains isbn number. The isbn number in "books" is primary key in "bookDetails" collection. I want bookName and author from the above document using join (aggregate in mongodb). The "books" and "bookDetails" collection are as follows :

"books"

 {
   "_id": 10001,
   "issued": true,
   "isbn": 1177009,
   "issuedIds": []
 }

"bookDetails"

{
  "_id": 1177009,
  "quantity": 5,
  "available": 5,
  "tags": [
           "cse",
           "ece",
           "me",
           "ce",
           "ee",
           "sems 1"
          ],
  "bookIds": [
              10001,
              10002,
              10003,
              10004,
              10005
             ],
  "bookName": "book 1",
  "author": "author 1"
}

I am working with nodejs and mongodb.

Ashh
  • 44,693
  • 14
  • 105
  • 132

1 Answers1

0

Thanks all. I got the answer.Please tell me if something is wrong because I got the required output.

database
  .collection('issueCart')
  .aggregate([
              {
                $match: {uid: parseInt(id)}
              },
              {
                $lookup: {
                           from: "bookDetails",
                           localField: "_id",
                           foreignField: "bookIds",
                           as: "book"
                         },
              },
              {
                $unwind: "$book"
              },
              {
                $replaceRoot: {
                         newRoot: {
                             $mergeObjects: ["$book", "$$ROOT"]
                         }
                   }
               },
               {
                 $project: {"bookId": "$_id", author: "$author", name: "$bookName", _id: 0}
               }
             ])