$elemMatch获取数组中的特定值



我有一个名为"考勤"的集合,它有一个数组:

[
{
"faculty": "20XX-XXXXX-XX-1",
"sections": [
{
"section": "XXXX 3-1",
"date": "04-11-2022",
"attendance": [
{
"number": "XXXXX",
"status": "Present"
},
{
"number": "XXXXX",
"status": "Present"
},
{
"number": "XXXXX",
"status": "Present"
}
]
},
{
"section": "XXXX 3-2",
"date": "04-11-2022",
"attendance": [
{
"number": "XXXXX",
"status": "Present"
},
{
"number": "XXXXX",
"status": "Present"
},
{
"number": "XXXXX",
"status": "Present"
}
]
}
]
}
]

我一直在尝试使用$and和$elemMatch-in:查询数组中特定元素的值

db.attendance.find({$and:[{faculty:"20XX-XXXXX-XX-1"},{sections:{$elemMatch:{section:"XXXX 3-1",date:"04-11-2022"}}}]});

但它仍然打印另一部分而不是一部分。我想输出为:

{
"faculty": "20XX-XXXXX-XX-1",
"sections": [
{
"section": "XXXX 3-1",
"date": "04-11-2022",
"attendance": [
{
"number": "XXXXX",
"status": "Present"
},
{
"number": "XXXXX",
"status": "Present"
},
{
"number": "XXXXX",
"status": "Present"
}
]
}

我试着使用点符号,比如:

db.attendance.find({"sections.section":"XXXX 3-1", "sections.date":"04-11-2022});

仍然没有运气。我不确定我所做的是对是错。提前感谢!

选项1:查找/elemMatch->您还需要将$elemMatch添加到查找查询的项目部分,如下所示:

db.collection.find({
"faculty": "20XX-XXXXX-XX-1",
sections: {
$elemMatch: {
section: "XXXX 3-1",
date: "04-11-2022"
}
}
},
{
sections: {
$elemMatch: {
section: "XXXX 3-1",
date: "04-11-2022"
}
}
})

解释:

Find查询具有以下语法:db.collection.Find({query},{project}(添加项目部分可以过滤预期的输出。

操场选项1

选项2:通过聚合/$filter:

db.collection.aggregate([
{
"$addFields": {
"sections": {
"$filter": {
"input": "$sections",
"as": "s",
"cond": {
$and: [
{
$eq: [
"$$s.section",
"XXXX 3-1"
]
},
{
$eq: [
"$$s.date",
"04-11-2022"
]
}
]
}
}
}
}
}
])

计划外:

将原始剖面阵列替换为新剖面阵列,其中阵列元素将根据提供的条件进行筛选。

操场选项2

最新更新