Mongodb 如何在数组中获取匹配的嵌套项

Mongodb 如何在数组中获取匹配的嵌套项,mongodb,Mongodb,如何在数组中获取匹配的嵌套项 我想返回嵌套数组中的匹配项 例如,我想筛选出在其项中包含“A428”、“A429”的记录 我怎么能得到它 查询 样本文件 预期结果 失败,错误为{“errmsg”:“异常:管道阶段规范对象必须仅包含一个字段。”,“代码”:16435,“确定”:0} 您应该首先记录,然后匹配元素,如下所示: db.collection.aggregate({ "$unwind": "$records" }, { "$match": { "records.ite

如何在数组中获取匹配的嵌套项

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

例如,我想筛选出在其项中包含
“A428”、“A429”
的记录

我怎么能得到它

查询 样本文件 预期结果 失败,错误为{“errmsg”:“异常:管道阶段规范对象必须仅包含一个字段。”,“代码”:16435,“确定”:0} 您应该首先
记录
,然后
匹配
元素,如下所示:

db.collection.aggregate({
    "$unwind": "$records"
}, {
    "$match": {
    "records.items": {
        "$in": ["A428 ", "A429 "]
    }
    }
}, {
    "$group": {
    "_id": "$_id",
    "records": {
        "$push": "$records"
    }
    }
}).pretty()

请检查以下查询:

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

首先记录
数组,然后匹配Hi您的解决方案将失败,因为“管道阶段规范对象必须只包含一个字段”。`@newBike否,它将为您提供预期的输出。你试过了吗?仅当您尝试将任何内容推送到
\u id
之外时,才会发生此异常。
  "_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
  }
];
db.collection.aggregate({
    "$unwind": "$records"
}, {
    "$match": {
    "records.items": {
        "$in": ["A428 ", "A429 "]
    }
    }
}, {
    "$group": {
    "_id": "$_id",
    "records": {
        "$push": "$records"
    }
    }
}).pretty()
 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" } } }
 ]);