json 使用MongoDB从嵌套对象数组中获取单个子对象

68de4m5k  于 2023-02-06  发布在  Go
关注(0)|答案(1)|浏览(144)

我有一个使用express和mongoose的node.js服务器,我还有一个Json结构:

[
    {
        "_id": "63dbaf5daabee478202ae59f",
        "experimentId": "85a91abe-ef2f-416f-aa13-ec1bdf5d9766",
        "experimentData": [
            {
                "scanId": 1652890241,
                "scanData": [
                    {
                        "areaName": "A1",
                        "areaData": [],
                        "_id": "63dbaf94aabee478202ae5a5"
                    },
                    ...
                ],
                "_id": "63dbaf6caabee478202ae5a3"
            },
            ...
        ],
        "__v": 2
    },
   ...
]

如何创建查询以从scanData数组返回单个对象,例如

{
          "areaName": "A1",
          "areaData": [],
          "_id": "63dbb006e322869df811eea4"
        }

我能做的最好的事是:

// * Get all shapes in a well/area
// ! uses the experiment id, scan id and areaName
router.get("/:id/scan/:scanId/area/:areaName", async (req, res) => {
    try {
        const experiment = await Experiment.findOne({
            experimentId: req.params.id,
            experimentData: {
                $elemMatch: {
                    scanId: req.params.scanId,
                    scanData: {
                        $elemMatch: {
                            areaName: req.params.areaName
                        }
                    }
                }
            }
        }, {'experimentData.scanData.$': 1})
        console.log(experiment)
        if (!experiment || experiment.length === 0) res.status(404).json({})
        else {
            res.send(experiment.experimentData[0])
        }
    } catch (err) {
        res.status(500).json({ message: err.message })
    }
})

但这只是返回了scanData数组,如果我能再深入一层,只获取具有areaName的对象,那就太好了。我还尝试了一些使用$aggregate的解决方案,但无法显示任何数据,因为它一直返回空数组

bqf10yzr

bqf10yzr1#

您可以按您的条件逐层执行$match,并使用$unwind获取聚合管道中的最终scanData对象。使用$replaceRoot仅获取scanData对象。

db.collection.aggregate([
  {
    "$match": {
      "experimentId": "85a91abe-ef2f-416f-aa13-ec1bdf5d9766"
    }
  },
  {
    "$unwind": "$experimentData"
  },
  {
    "$match": {
      "experimentData.scanId": 1652890241
    }
  },
  {
    "$unwind": "$experimentData.scanData"
  },
  {
    "$match": {
      "experimentData.scanData.areaName": "A1"
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$experimentData.scanData"
    }
  }
])

Mongo Playground

相关问题