以下是我正在进行的名为测试的集合,我需要让所有正在进行DOB的人员参加" 24-04-1973"
{
"year": "1973",
"allPersons": [
{
"name": "First guy",
"DOB": "24-04-1973"
},
{
"name" : "Second guy",
"DOB": "02-12-1973"
}
{
"name": "Third guy",
"DOB": "13-01-1973"
},
{
"name": "Fourth guy",
"DOB": "24-04-1973"
},
{
"name": "Fifth guy",
"DOB": "24-04-1973"
},
]
}
但我只能通过以下查询从allPersons
数组中获取第一个对象
db.testing.find(
{
"allPersons.DOB":"24-04-1973"
},
{
_id:0,"allPersons":
{
$elemMatch:
{
"DOB":'24-04-1973'
}
}
}
).pretty();
以上查询的结果
{
"allPersons" : [
{
"name" : "First guy",
"DOB" : "24-04-1973"
}
]
}
但我期望获得的结果是让所有DOB
"24-04-1973"
的人都在下面
{
"allPersons" : [
{
"name" : "First guy",
"DOB" : "24-04-1973"
},
{
"name" : "Fourth guy",
"DOB" : "24-04-1973"
},
{
"name" : "Fifth guy",
"DOB" : "24-04-1973"
}
]
}
是否有人知道正确的查询以生成上述类型的结果
mongo Db版本2.6.11
我是新来的,请原谅,如果它是愚蠢的
答案 0 :(得分:2)
尝试以下脚本:
db.doc.aggregate([
{$unwind:"$allPersons"},
{$match:{"allPersons.DOB":"24-04-1973"}},
{$group:{_id:{id:"$_id", year:"$year"}, allPersons:{$push:"$allPersons"}}},
{$project:{_id:0, allPersons:1}}
])
会发出:
{
"allPersons" : [
{
"name" : "First guy",
"DOB" : "24-04-1973"
},
{
"name" : "Fourth guy",
"DOB" : "24-04-1973"
},
{
"name" : "Fifth guy",
"DOB" : "24-04-1973"
}
]
}