【问题标题】:Can't find right query for MongoDB using mongo shell使用 mongo shell 找不到 MongoDB 的正确查询
【发布时间】:2018-07-16 10:34:43
【问题描述】:

我一直在尝试获取拥有每种药物的最新(根据其建立日期)药房的列表。

将此输出作为以下文档数组的结果作为样本:

输出:
医学 : MedA , 药学 : a
医学 : MedB , 药学 : b
医学 : MedC , 药学 : b
医学:医学博士,药学:a

[
  {
    "Pharmacy": "a",
    "EstablishedDate": ISODate("2006-10-12"),
    "Medicine": [
      {
        "MedName": "MedA",
        "Quantity": 55
      },
      {
        "MedName": "MedB",
        "Quantity": 34
      },
      {
        "MedName": "MedD",
        "Quantity": 25
      }
    ]
  },
  {
    "Pharmacy": "b",
    "EstablishedDate": ISODate("2015-2-2"),
    "Medicine": [
      {
        "MedName": "MedB",
        "Quantity": 60
      },
      {
        "MedName": "MedC",
        "Quantity": 34
      }
    ]
  }
]

如何解决?

【问题讨论】:

标签: node.js mongodb mongoose mongodb-query mongo-shell


【解决方案1】:

1.各药店所有药品的答案

db.collection.aggregate([
  {
    $unwind: "$Medicine"
  },
  {
    $project: {
      "_id": 0,
      "Medicine": "$Medicine.MedName",
      "Pharmacy": "$Pharmacy"
    }
  }
])

输出

[
  {
    "Medicine": "MedA",
    "Pharmacy": "a"
  },
  {
    "Medicine": "MedB",
    "Pharmacy": "a"
  },
  {
    "Medicine": "MedD",
    "Pharmacy": "a"
  },
  {
    "Medicine": "MedB",
    "Pharmacy": "b"
  },
  {
    "Medicine": "MedC",
    "Pharmacy": "b"
  }
]

参考playground 并运行脚本

2.最新药房的所有药品

db.collection.aggregate([
  {
    $unwind: "$Medicine"
  },
  {
    $sort: {
      EstablishedDate: -1
    }
  },
  {
    $group: {
      _id: "$Medicine.MedName",
      Pharmacy: {
        $first: "$Pharmacy"
      }
    }
  },
  {
    $project: {
      _id: 0,
      "Medicine": "$_id",
      "Pharmacy": "$Pharmacy"
    }
  }
])

输出

[
  {
    "Medicine": "MedA",
    "Pharmacy": "a"
  },
  {
    "Medicine": "MedC",
    "Pharmacy": "b"
  },
  {
    "Medicine": "MedD",
    "Pharmacy": "a"
  },
  {
    "Medicine": "MedB",
    "Pharmacy": "b"
  }
]

参考各自的playground 并运行脚本

【讨论】:

  • 如果我只想显示 最新 药房有药品,我需要做什么,例如 MedB 只会显示药房“b”,因为它的 比药房“a”新
  • 如果你喜欢我的努力,我已经更新了我的答案并批准答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
相关资源
最近更新 更多