2

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 ?

2 Answers 2

1

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"
      ]
    }
  }}
])
Sign up to request clarification or add additional context in comments.

Comments

1

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,
        }
      }
    ])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.