我需要根据数组中最后一个元素的属性上的状态代码检索订单。
我的结构如下。
{
"_id" : "3580bdba-4017-40af-939d-7391d70b3511",
"IsPublic" : true,
"MailReceiptDispatch" : {
"TransferSupervisor" : {
"TransferStatuses" : [{
"TransferState" : 0,
"TransferTime" : ISODate("2015-05-29T11:21:20.722Z")
}, {
"TransferState" : 1,
"TransferTime" : ISODate("2015-05-29T11:54:10.013Z")
}, {
"TransferState" : 2,
"TransferTime" : ISODate("2015-05-29T11:54:12.462Z")
}],
"IsTransferedLimitReached" : false,
"LatestTransferingStatus" : {
"TransferState" : 2,
"TransferTime" : ISODate("2015-05-29T11:54:12.462Z")
}
},
"ExceptionLog" : [],
"HasWarningBeenSent" : false
}
}
所以我需要根据以下内容获取所需的对象: {MailReceiptDispatch.TranferSupervisor.TransferStatuses。[在数组中获取最后一个] .TransferState:2}`
我尝试了slice
,但后来我只是检索了这个对象。我需要查看objects属性。 ElemMatch
做了一些可能有用的事情,但我无法弄清楚如何连接切片和ElemMatch。
答案 0 :(得分:1)
Mongo Aggregation用于查找最后TransferState
,首先是unwind TransferStatuses
数组,并在聚合中使用sort
或max
获取最新TransferState
,如下所示:
1>对聚合中的所有TransferTime
进行排序:
db.collectionName.aggregate({"$unwind":"$MailReceiptDispatch.TransferSupervisor.TransferStatuses"},
{"$sort":{"MailReceiptDispatch.TransferSupervisor.TransferStatuses.TransferTime":-1}},
{"$group":{"_id":"$_id","TransferState":{"$first":"$MailReceiptDispatch.TransferSupervisor.TransferStatuses.TransferState"},
"TransferTime":{"$first":"$MailReceiptDispatch.TransferSupervisor.TransferStatuses.TransferTime"}}}
).pretty()
2 - ;在汇总中使用max
:
db.collectionName.aggregate({"$unwind":"$MailReceiptDispatch.TransferSupervisor.TransferStatuses"},
{"$group":{"_id":"$_id","TransferState":{"$max":"$MailReceiptDispatch.TransferSupervisor.TransferStatuses.TransferState"},
"TransferTime":{"$max":"$MailReceiptDispatch.TransferSupervisor.TransferStatuses.TransferTime"}}}
).pretty()