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

时间:2019-01-30 11:11:13

标签: node.js mongodb mongoose aggregation-framework

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

(使用整数表示对象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 }
    ]
  }
  ...
]

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

即:

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

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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"
      ]
    }
  }}
])