【发布时间】:2015-06-23 03:47:22
【问题描述】:
如何在数组中获取匹配的嵌套项
我想返回嵌套数组中的匹配项。
例如,我想过滤掉 items
中包含"A428 ","A429 " 的记录
我怎么能得到它?
查询
pipeline_work = [
{ '$match': 'records.items': '$in': ["A428 ","A429 "])}
]
cur = db[source_collection].runCommand('aggregate',pipeline: pipeline_work , allowDiskUse: true)
示例文档
{
"_id": "0007db2dac8d6482ec60c228b700c3ec",
"records": [
{
"APPL_DATE": new Date("1996-03-19T08:00:00+0800"),
"FUNC_DATE": new Date("1996-02-27T08:00:00+0800"),
"items": [
"A428 ",
" ",
" "
]
},
{
"APPL_DATE": new Date("1996-03-19T08:00:00+0800"),
"FUNC_DATE": new Date("1996-02-27T08:00:00+0800"),
"items": [
"A429 ",
" ",
" "
]
},
{
"APPL_DATE": new Date("1996-04-15T08:00:00+0800"),
"FUNC_DATE": new Date("1996-03-18T08:00:00+0800"),
"items": [
"A180 ",
" ",
" "
]
}]
预期结果
"_id": "0007db2dac8d6482ec60c228b700c3ec",
"records": [
{
"APPL_DATE": new Date("1996-03-19T08:00:00+0800"),
"FUNC_DATE": new Date("1996-02-27T08:00:00+0800"),
"items": [
"A428 ",
" ",
" "
]
},
{
"APPL_DATE": new Date("1996-03-19T08:00:00+0800"),
"FUNC_DATE": new Date("1996-02-27T08:00:00+0800"),
"items": [
"A429 ",
" ",
" "
]
}]
因 {"errmsg":"exception: 管道阶段规范对象必须只包含一个字段而失败。","code":16435,"ok":0}
pipeline_work = [
{
"$unwind": "$records",
"$match": {
"records.items": {
"$in": ["A428 ", "A429 "]
}
},
"$group": {
"_id": "$_id",
"records": {
"$push": "$records"
}
}
}, {
'$limit': 1
}
];
【问题讨论】:
-
$unwind
records先数组再match
标签: mongodb