我怎样才能在数组中获得匹配的嵌套项

时间:2015-06-23 03:47:22

标签: mongodb

如何在数组

中获取匹配的嵌套项

我想在嵌套数组中返回匹配的项目。

例如,我想过滤掉

中包含"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“:”异常:管道阶段规范对象必须只包含一个字段。“,”code“:16435,”ok“:0}

pipeline_work = [
  {
    "$unwind": "$records",
    "$match": {
      "records.items": {
        "$in": ["A428 ", "A429 "]
      }
    },
    "$group": {
      "_id": "$_id",
      "records": {
        "$push": "$records"
      }
    }
  }, {
    '$limit': 1
  }
];

2 个答案:

答案 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" } } }
 ]);