【问题标题】:How to properly unwind my array in mongodb如何在 mongodb 中正确展开我的数组
【发布时间】:2019-12-13 14:36:34
【问题描述】:

我需要解开我的处方,以便获得每个处方的总计数

这是我的插入之一

{
    "_id" : 1,
    "patient" : {
        "name" : "Locke, John",
        "id": 1,
        "sex": "male",
        "age": 52
    },
    "doctor": {
        "name" : "Grey, Meredith",
        "id": 12,
        "specialty": "general",
        "age": 42
    },
    "hospital": {
        "name" : "Seattle Grace",
        "id": 4,
        "location": {
            "street": "5th avenue",
            "city": "Taguig",
            "region": "Metro Manila",
            "zip code": 1634
            }
    },
    "date": {
        "month": 12,
        "date": 12,
        "year": 2019
    },
    "emergency_type": "non-emergent",
    "emergency_case": "severe headache",
    "waiting_time": 5123,
    "treatment": {
        "id": 1,
        "prescription": ["biogesic", "bed rest"]
    }

这是我一直在尝试解决的展开代码,但我无法让它工作。

 db.healthcare.aggregate([
  {
    $unwind: { path: "$prescription"}
  },
  {
    "$group": {
    "_id": "$treatment.prescription",
    "total prescriptions": { "$sum": 1 }
    }
  }

【问题讨论】:

标签: database mongodb nosql nosql-aggregation


【解决方案1】:

$unwind路径不对,应该是$treatment.prescription

db.healthcare.aggregate([
  {
    $unwind: {
      path: "$treatment.prescription"
    }
  },
  {
    "$group": {
      "_id": "$treatment.prescription",
      "total prescriptions": {
        "$sum": 1
      }
    }
  },
  {
    $sort: {
      "total prescriptions": -1
    }
  },
  {
    "$limit": 3
  }
])

【讨论】:

  • 效果很好,非常感谢!我如何限制它以按升序显示前 3 个最常用的?
猜你喜欢
  • 1970-01-01
  • 2014-04-02
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
  • 2022-01-10
  • 2023-03-30
  • 2017-03-03
  • 2017-01-15
相关资源
最近更新 更多