Mongodb 需要帮助查询mongo上的嵌套数组吗
我在mongo db中有以下文档结构Mongodb 需要帮助查询mongo上的嵌套数组吗,mongodb,sub-array,Mongodb,Sub Array,我在mongo db中有以下文档结构 { "_id": { "name": "XYX", "rol_no": "1", "last_update_dt": "2021-05-10", }, "stud_history": [{ 'std': 'xyz', 'age': '16' }, {
{
"_id": {
"name": "XYX",
"rol_no": "1",
"last_update_dt": "2021-05-10",
},
"stud_history": [{
'std': 'xyz',
'age': '16'
},
{
'std': 'mnl',
'age': '15'
}]
}
我想查询像这样的数据
name:xyz, rol_no:1, last_update_dt: 2021-05-10 and age:16
这里我只提到了一个学生,但我需要对多个学生进行类似的查询
因此,我的输出将是
"_id": {
"name": "XYX",
"rol_no": "1",
"last_update_dt": "2021-05-10",
},
'stud_history': {
'std': 'xyz',
'age': '16'
}
请提供帮助您必须在match命令的投影参数中使用
$elemMatch
运算符来筛选与特定条件匹配的输出
db.collection.find({ // Find Query
"_id.name": "XYX",
"_id.rol_no": "1",
"_id.last_update_dt": "2021-05-10",
},
{ // Projection Parameter
"_id": 1,
"stud_history": {
"$elemMatch": { // Filters array elements to those matching the provided condition
"age": "16"
}
}
})
如果要使用聚合实现相同的效果,请使用以下查询:
db.collection.aggregate([
{
"$match": {
"_id.name": "XYX",
"_id.rol_no": "1",
"_id.last_update_dt": "2021-05-10",
}
},
{
"$project": {
"_id": 1,
"stud_history": {
$filter: {
input: "$stud_history",
as: "item",
cond: {
$eq: [ "$$item.age", "16" ]
}
}
}
}
},
{
// If you want the result to be an object instead of an array
"$unwind": "$stud_history"
},
])
你能发布聚合吗?在答案中添加聚合示例