gpt4 book ai didi

MongoDB:按嵌套数组中的最新项目查找文档

转载 作者:行者123 更新时间:2023-12-02 01:06:41 24 4
gpt4 key购买 nike

我有一个包含具有下一个结构的文档的集合:

 {
"Id" : 123
"History" : [
{
"MachineId" : 1,
"Time" : ISODate("2014-02-10T13:10:00Z"),
"Status" : 0
},
{
"MachineId" : 1,
"Time" : ISODate("2014-02-10T13:10:44Z"),
"Status" : 1
},
{
"MachineId" : 2,
"Time" : ISODate("2014-02-10T13:10:50Z"),
"Status" : 2
}
]
},
{
"Id" : 345
"History" : [
{
"MachineId" : 1,
"Time" : ISODate("2014-02-10T13:10:00Z"),
"Status" : 0
},
{
"MachineId" : 1,
"Time" : ISODate("2014-02-10T13:10:44Z"),
"Status" : 1
}
]
}

我有一个输入 MachineIdStatus,我想找到所有具有给定 MachineId 的嵌套历史记录项的文档>状态,但此项必须是最新的。

例如,对于MachineId=1Status=1,我只想获取Id=345

的文档

我知道如何查询嵌套数组元素,但在这里我需要先对历史数组进行排序以找到最后添加的项目。我不知道如何在 MongoDB 中执行此操作。

最佳答案

既然你说你不知道如何处理这个问题,我会试着引导你完成。这非常适合 aggregation pipeline :

db.history.aggregate([
// Match the item you want while you can still use an index
{$match: { "History.MachineId" : 1, "Id" : 345 } },

// ** Denormalise ** the array entries for additional processing
{$unwind: "$History" },

// Order things so the last time is first
{$sort: { "History.Time": -1 }},

// Filter out the first item per document
{$group: { _id: "$Id", Time: {$first: "$History.Time" } }}
])

如果您需要比返回的信息更多的信息,那么您可以查看 this question有关如何改变结果形状的一些指示。

关于MongoDB:按嵌套数组中的最新项目查找文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21754081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com