我有一个这样的样本集合:
{
"_id" : ObjectId("58d6cbc14124691cd8154d72"),
"correlativeCode" : "CSLLPA53E20M017W",
"registrationMethod" : "taken",
"originPlace" : "INSPI",
"temperature" : 16,
"sampleStatus" : [
{
"nameStatus" : "status1",
"place" : "place1",
"rejectionReason" : "Nothing",
"user" : "user1",
"_id" : ObjectId("58d6cbc14124691cd8154d73")
},
{
"nameStatus" : "status2",
"place" : "place2",
"rejectionReason" : "Nothing",
"user" : "user4",
"_id" : ObjectId("58d6cbc14124691cd8154d73")
},
{
"nameStatus" : "status3",
"place" : "place3",
"rejectionReason" : "Nothing",
"user" : "user3",
"_id" : ObjectId("58d6cbc14124691cd8154d73")
},
{
"nameStatus" : "status4",
"place" : "place4",
"rejectionReason" : "Nothing",
"user" : "user1",
"_id" : ObjectId("58d6cbc14124691cd8154d73")
},
{
"nameStatus" : "status5",
"place" : "place5",
"rejectionReason" : "Nothing",
"user" : "user5",
"_id" : ObjectId("58d6cbc14124691cd8154d73")
}
]
}
首先,我想通过 correlativeCode 找到一个样本(这很容易)但是..然后 我需要获取 sampleStatus 的最后一个元素并检查 sampleStatus 数组的用户字段是否等于表达式(另一个用户)。
sampleStatus 数组的长度是可变的。
我试过 $slice 命令,但效果不佳。
例如,
如果我找到一个相关代码为“CSLLPA53E20M017W”的样本,其中最后一个 sampleStatus.user 是 user1,它应该获取 0 条记录。
但是如果我找到一个相关代码为“CSLLPA53E20M017W”的样本,其中最后一个 sampleStatus.user 是 user5,它应该获取 1 条记录。
请帮帮我,我卡住了。
最佳答案
你可以用聚合框架做到这一点
db.collection.aggregate([
{ "$match": { "correlativeCode": "CSLLPA53E20M017W" } },
{ "$redact": {
"$cond": [
{ "$eq": [
{ "$let": {
"vars": {
"item": { "$arrayElemAt": [ "$sampleStatus", -1 ] }
},
"in": "$$item.user"
} },
"user5"
] },
"$$KEEP",
"$$PRUNE"
]
}}
])
关于arrays - 如何检查数组中的最后一个元素是否符合条件,mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43164668/