MongoDB 嵌套数组查找和投影

MongoDB nested Array find and projection

我目前正在使用 mongodb (mongoose)。我的示例文档之一是:

myuser{
  _id: 7777...,
  money: 1000,
  ships:[{
    _id: 7777...
    name: "myshipname",
    products:[{
      product_id: 7777....,
      quantity: 24
    }]
  }
}

我的目标是获得某个产品给定的用户ID、发货ID和产品ID,结果类似于:{ product_id: 777..,quantity:24}

到目前为止,我找到了某个用户:

findOne(userId,ships:{ $elemMatch: {_id:shipId}})

其中 returns 数组 ships 中带有 shipId 的船的信息来自具有 userId 的用户。但是,我找不到从那艘船上只获得某种产品的方法

您想要的可能最好使用聚合框架来完成。类似于:

db.users.aggregate([
  {$match: { _id : <user>}},
  {$unwind: "$ships"},
  {$unwind: "$ships.products"},
  {$match: { "ships._id": <ship>}},
  {$match: { "ships.products.product_id": <product>}}
]);

请注意,我现在不在使用 mongo 的计算机上,所以我的语法可能有点偏差。