如何在数组
中获取匹配的嵌套项我想在嵌套数组中返回匹配的项目。
例如,我想过滤掉项
中包含"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 ",
" ",
" "
]
}]
pipeline_work = [
{
"$unwind": "$records",
"$match": {
"records.items": {
"$in": ["A428 ", "A429 "]
}
},
"$group": {
"_id": "$_id",
"records": {
"$push": "$records"
}
}
}, {
'$limit': 1
}
];
答案 0 :(得分:1)
您应首先$unwind records
然后match
元素如下:
db.collection.aggregate({
"$unwind": "$records"
}, {
"$match": {
"records.items": {
"$in": ["A428 ", "A429 "]
}
}
}, {
"$group": {
"_id": "$_id",
"records": {
"$push": "$records"
}
}
}).pretty()
答案 1 :(得分:1)
请检查以下查询:
db.collection.aggregate([
{"$unwind" : "$records"},
{"$unwind" : "$records.items"},
{"$match" : {"records.items" : {"$in" : [ "A428 ","A429 "] } } },
{"$group" : { "_id" : { "id" : "$_id" , "app_date" : "$records.APPL_DATE" ,
"fun_date" : "$records.FUNC_DATE"} ,
"records_temp" : { "APPL_DATE" : { "$first" :"$records.APPL_DATE" },
"FUNC_DATE" : { "$first" : "$records.FUNC_DATE" } ,
"items" : {"$push" : "$records.items"} } },
{"$group" : { "_id" : "$_id.id", "records" : { "$push" : "$records_temp" } } }
]);