首页 > 解决方案 > 从 MongoDB 中获取嵌套数据

问题描述

我有一个以下格式的集合。

{
    "_id": "ffffc446-f33d",
    "className": "com.ezdx.vist.model.Visit",
    "organizationId": "0a0beff7-fe1e-4ab7",
    "centerId": "9aef68fe-dffd-4a7d-b0ee-f8dd3fc03303",
    "tests": [{
            "result": 157,
            "type": "PHYSICAL",
            **"name": "HEIGHT",**
            "consumableQuantity": 0,
            "testCost": 0,
            "testExpenseConsumable": 0

        },
        {
            "result": 8,
            "type": "RDT",
            **"name": "URIC",**
            "consumableQuantity": 0,
            "testCost": 0,
            "testExpenseConsumable": 0
        }

    ],
    "repeatVisit": true
}

我想要 test.name = "Uric" 和特定列的集合。

  {
    "result": 8,
    "type": "RDT",
    **"name": "Uric",**
    "consumableQuantity": 0,
    "testCost": 0,
    "testExpenseConsumable": 0
}

不知何故,我设法获得了所需的收藏,但我无法获得所需的格式。以下是我的查询

db.visits.aggregate( [ { $unwind : "$tests" }, 
{ $match: { $and: [{"tests.name":"URIC"}]
    } } ] )

标签: mongodbmongodb-query

解决方案


试试这个:$replaceWith (=v4.2) 或$replaceRoot (>=v3.4)

db.visits.aggregate([
  {
    $unwind: "$tests"
  },
  {
    $match: {
      "tests.name": "URIC"
    }
  },
  {
    $replaceWith: "$tests"
  }
])

Mongo游乐场


推荐阅读