[英]How to access nested array of objects in mongodb aggregation pipeline?
I have a document like this(this is the result after few pipeline stages)我有一个这样的文档(这是几个流水线阶段后的结果)
[
{
"_id": ObjectId("5e9d5785e4c8343bb2b455cc"),
"name": "Jenny Adams",
"report": [
{ "category":"Beauty", "status":"submitted", "submitted_on": [{"_id": "xyz", "timestamp":"2022-02-23T06:10:05.832+00:00"}, {"_id": "abc", "timestamp":"2021-03-23T06:10:05.832+00:00"}] },
{ "category":"Kitchen", "status":"submitted", "submitted_on": [{"_id": "mnp", "timestamp":"2022-05-08T06:10:06.432+00:00"}] }
]
},
{
"_id": ObjectId("5e9d5785e4c8343bb2b455db"),
"name": "Mathew Smith",
"report": [
{ "category":"Household", "status":"submitted", "submitted_on": [{"_id": "123", "timestamp":"2022-02-23T06:10:05.832+00:00"}, {"_id": "345", "timestamp":"2021-03-23T06:10:05.832+00:00"}] },
{ "category":"Garden", "status":"submitted", "submitted_on": [{"_id": "567", "timestamp":"2022-05-08T06:10:06.432+00:00"}] },
{ "category":"BakingNeeds", "status":"submitted", "submitted_on": [{"_id": "891", "timestamp":"2022-05-08T06:10:06.432+00:00"}] }
]
}
]
I have user input for time period -我有时间段的用户输入 -
from - 2021-02-23T06:10:05.832+00:00
to - 2022-02-23T06:10:05.832+00:00
Now I wanted to filter the objects from the report which lie in a certain range of time, I want to only keep the object if the "submitted_on[-1]["timestamp"]"
is in range of from and to date timestamp.现在我想从报告中过滤出某个时间范围内的对象,如果"submitted_on[-1]["timestamp"]"
在从和到日期时间戳的范围内,我只想保留 object。 I am struggling with accessing the timestamp because of the nesting I tried this由于我试过这个嵌套,我正在努力访问时间戳
$project: {
"name": 1,
"report": {
"category": 1,
"status": 1,
"submitted_on": 1,
"timestamp": {
$arrayElemAt: ["$report.cataloger_submitted_on", -1]
}
}
}
But this gets the last object of the report array {"_id": "bcd", "timestamp":"2022-05-08T06:10:06.432+00:00"}
for all the items inside the report.但这会获取报告中所有项目的报告数组{"_id": "bcd", "timestamp":"2022-05-08T06:10:06.432+00:00"}
的最后一个 object。 How can I do this to select the last timestamp of each obj.我怎样才能做到这一点 select 每个对象的最后一个时间戳。
You can replace your phase in the aggregation pipeline with two phases: $unwind
and $addFields
in order to get what I think you want:您可以用两个阶段替换聚合管道中的阶段: $unwind
和$addFields
以获得我认为您想要的:
{
$unwind: "$report"
},
{
"$addFields": {
"timestamp": {
$arrayElemAt: [
"$report.submitted_on",
-1
]
}
}
},
The $unwind
phase is breaking the external array into documents since you want to perform an action on each one of them. $unwind
阶段将外部数组分解为文档,因为您要对每个文档执行一个操作。 See the playground here with your example.以您的示例在此处查看游乐场。 If you plan to continue the aggregation pipeline with more steps, you can probably skip the $addFields
phase and include the condition inside your next $match
phase.如果您计划通过更多步骤继续聚合管道,您可以跳过$addFields
阶段并将条件包含在下一个$match
阶段中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.