使用mongo shell无法找到正确的MongoDB查询

时间:2018-07-16 10:34:44

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

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

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

  

输出:
   医药:MedA,药学:a
   医药:MedB,药学:b
   医药:MedC,药学:b
   医学:MedD,药学: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
      }
    ]
  }
]

如何解决?

1 个答案:

答案 0 :(得分: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并运行脚本