简体   繁体   English

MongoDB - 如何从具有 ID 的对象数组中检索多个集合

[英]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) (使用整数表示对象 ID)

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.现在,当请求发送到我的服务器时,在req.body包含customerID ,我想为该客户返回推荐的书籍,并附加可能性。

ie : IE :

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 ?请问,实现此目的的 MongoDB 聚合查询是什么?

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

You can use below aggregation您可以使用以下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"
      ]
    }
  }}
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM