簡體   English   中英

從 MongoDB 中獲取嵌套數據

[英]Fetch nested data from 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"}]
    } } ] )

試試這個: $replaceWith (=v4.2) 或$replaceRoot (>=v3.4)

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

蒙戈游樂場

作為 Valijon 答案的替代方案,您可以使用$filter聚合,這可能會更快,因為我們沒有應用 $unwind。

db.collection.aggregate([
  {
    $project: {
      items: {
        $filter: {
          input: "$tests",
          as: "item",
          cond: {
            $eq: [
              "$$item.name",
              "URIC"
            ]
          }
        }
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $arrayElemAt: [
          "$items",
          0
        ]
      }
    }
  }
])

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM