【问题标题】:MongoDB nested Array find and projectionMongoDB 嵌套数组查找和投影
【发布时间】:2016-02-14 06:40:41
【问题描述】:

我目前正在使用 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}})

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

【问题讨论】:

    标签: mongodb mongoose database nosql


    【解决方案1】:

    您想要的最好使用聚合框架来完成。比如:

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

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

    【讨论】:

      猜你喜欢
      • 2015-05-12
      • 2021-01-28
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2015-06-20
      相关资源
      最近更新 更多