Kingsley CA
Kingsley CA

Reputation: 11634

MongoDB - How to retrieve multiple collections from an array of objects that have their IDs

So, I have a database with the following collections.

(Using Integers to represent the object IDs)

Books:

books = [
  { _id: 1, title: "Harry Potter" },
  { _id: 2, title: "The maze runner" }
  ...
]

Customers:

customers = [
  { _id: 1, name: "John" },
  { _id: 2, title: "Jane"}
  ...
]

Recommendations:

recommendations = [
  {
    customerID: 1,
    recommendations: [
      { bookID: 1, likelihood: 0.9 },
      { bookID: 2, likelihood: 0.8 }
    ]
  },
  {
    customerID: 2,
    recommendations: [
      { bookID: 2, likelihood: 0.9 },
      { bookID: 1, likelihood: 0.8 }
    ]
  }
  ...
]

Now when a request is sent to my server, containing customerID in the req.body, i want to return the recommended books for that customer, with the likelihood appended to them.

i.e :

desiredResult = [
  {
    _id: 1,
    title: "Harry Potter",
    likelihood: 0.9
  },
  {
    _id: 2,
    title: "The maze Potter",
    likelihood: 0.8
  }
  ...
]

Please, what is the MongoDB aggregation query to achieve this ?

Upvotes: 2

Views: 49

Answers (2)

Ashok
Ashok

Reputation: 2932

Below Aggregation may help you

db.recommendations.aggregate([
      { $match: { "customerID": 1 } },
      { $unwind: "$recommendations" },
      { $lookup: {
          from: "books",
          localField: "recommendations.bookID",
          foreignField: "_id",
          as: "recomndedBook"
      }},
      {
        $addFields: {
          title: { $arrayElemAt: [ "$recomndedBook.title", 0 ] },
          likelihood: "$recommendations.likelihood",
          bookID: "$recommendations.bookID"
        }
      },
      { 
        $project: {
          recommendations: 0,
          recomndedBook: 0,
          _id: 0,
        }
      }
    ])

Upvotes: 1

Ashh
Ashh

Reputation: 46481

You can use below aggregation

db.recommendations.aggregate([
  { "$match": { "customerID": 1 }},
  { "$unwind": "$recommendations" },
  { "$lookup": {
    "from": "books",
    "localField": "recommendations.bookID",
    "foreignField": "_id",
    "as": "recomndedBook"
  }},
  { "$replaceRoot": {
    "newRoot": {
      "$mergeObjects": [
        { "$arrayElemAt": ["$recomndedBook", 0] },
        "$recommendations"
      ]
    }
  }}
])

Upvotes: 1

Related Questions