如何使用MongoDB聚合从嵌套对象中提取对象



我有对象数组形式的数据,对象包含review及其键值对,它有reviewDetail。以下是数据

[
{
"review": {
"reviewDetail": {
"title": "review 2",
"description": "this is description",
"file": [
"1659414826665-cropped-cropped-logo-e1620197043895-2.png.png"
],
"viewed": 0,
"isDeleted": true,
"_id": "62e8a92a0c6e7159a7b934d8",
"createdAt": "2022-08-02T04:33:46.677Z",
"updatedAt": "2022-08-02T04:37:28.213Z"
}
}
},
{
"review": {
"reviewDetail": {
"title": "review 1",
"description": "this is description of review",
"file": [
"1659414880490-cropped-cropped-logo-e1620197043895-2.png.png"
],
"viewed": 0,
"isDeleted": true,
"_id": "62e8a9600c6e7159a7b934df",
"createdAt": "2022-08-02T04:34:40.499Z",
"updatedAt": "2022-08-06T12:44:04.633Z"
}
}
},
{
"review": {
"reviewDetail": {
"title": "review 1",
"description": "this is description of review",
"file": [],
"viewed": 0,
"isDeleted": true,
"_id": "62ee5e76e9934990d6911e21",
"createdAt": "2022-08-06T12:28:38.457Z",
"updatedAt": "2022-08-06T13:24:03.074Z"
}
}
}
]

我想提取数组中的reviewDetails:以下是所需的结果

[
{
"title": "review 2",
"description": "this is description",
"file": [
"1659414826665-cropped-cropped-logo-e1620197043895-2.png.png"
],
"viewed": 0,
"isDeleted": true,
"_id": "62e8a92a0c6e7159a7b934d8",
"createdAt": "2022-08-02T04:33:46.677Z",
"updatedAt": "2022-08-02T04:37:28.213Z"
},
{
"title": "review 1",
"description": "this is description of review",
"file": [
"1659414880490-cropped-cropped-logo-e1620197043895-2.png.png"
],
"viewed": 0,
"isDeleted": true,
"_id": "62e8a9600c6e7159a7b934df",
"createdAt": "2022-08-02T04:34:40.499Z",
"updatedAt": "2022-08-06T12:44:04.633Z"
},
{
"title": "review 1",
"description": "this is description of review",
"file": [],
"viewed": 0,
"isDeleted": true,
"_id": "62ee5e76e9934990d6911e21",
"createdAt": "2022-08-06T12:28:38.457Z",
"updatedAt": "2022-08-06T13:24:03.074Z"
}
]

我试图在nodejs中使用Javascript提取特定模式,但需要使用聚合管道

您可以简单地使用它来实现您想要的输出

collectionName.aggregate([
{
$replaceRoot:{ newRoot:"$review.reviewDetail" }
}    
])

最新更新