【问题标题】:MongoDB - How to retrieve multiple collections from an array of objects that have their IDsMongoDB - 如何从具有 ID 的对象数组中检索多个集合
【发布时间】:2019-02-01 20:06:04
【问题描述】:

所以,我有一个包含以下集合的数据库。

(使用整数表示对象ID)

书籍:

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

客户:

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

建议:

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 }
    ]
  }
  ...
]

现在,当一个请求被发送到我的服务器时,在req.body 中包含customerID,我想为该客户返回推荐的书籍,并附上可能性。

即:

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

请问,实现此目的的 MongoDB 聚合查询是什么?

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    您可以在下面使用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"
          ]
        }
      }}
    ])
    

    【讨论】:

      【解决方案2】:

      下面Aggregation可能对你有帮助

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

      【讨论】:

        猜你喜欢
        • 2012-07-08
        • 1970-01-01
        • 2015-07-24
        • 2022-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-07
        • 1970-01-01
        相关资源
        最近更新 更多