在mongodb

时间:2017-11-13 10:37:43

标签: mongodb aggregation-framework

我提到了这个链接Retrieve only the queried element in an object array in MongoDB collection但是示例是从mongodb中的对象数组中检索一个元素。现在我想从数组的数组中检索一个元素,请帮我如何做同样的事情。

示例记录:

 {  
    "_id":ObjectId("562e7c594c12942f08fe4192"),
   "shapes":[  
  {  
     "shape":"square",
     "color":"blue",
     "fileArray:[
        {"fileid" : 'ID001',"filename" : "Abc.jpg", filepath" :"d:/temp/"},
        {"fileid" : 'ID002',"filename" : "Cde.jpg", filepath" :"d:/temp2/"}
      ]
  },
  {  
     "shape":"circle",
     "color":"red",
     "fileArray:[
        {"fileid" : 'ID003',"filename" : "Abc.jpg", filepath" :"d:/temp/"},
        {"fileid" : 'ID004',"filename" : "Cde.jpg", filepath" :"d:/temp2/"}
      ]
  }
   ]

 },

  {  
     "_id":ObjectId("562e7c594c12942f08fe4193"),

     "shapes":[  
  {  
     "shape":"square",
     "color":"black",
     "fileArray:[
        {"fileid" : 'ID001',"filename" : "Abc.jpg", filepath" :"d:/temp/"},
        {"fileid" : 'ID002',"filename" : "Cde.jpg", filepath" :"d:/temp2/"}
      ]
  },
  {  
     "shape":"circle",
     "color":"green",
     "fileArray:[
        {"fileid" : 'ID003',"filename" : "Abc.jpg", filepath" :"d:/temp/"},
        {"fileid" : 'ID004',"filename" : "Cde.jpg", filepath" :"d:/temp2/"}
      ]
  }
    ]
       }

我的要求是在fileid和shape.color为红色时找出文件路径和文件名。

正如Niell建议的链接Find in Double Nested Array MongoDB

    db.dummies.aggregate([

       { "$match": {
"shapes": {
  "$elemMatch": {
     "color": "blue",
     "fileArray": {
       "$elemMatch": {
         "fileid": "ID001"//,
         //"otherField": 1
       }
     }
   }
}
      }}

     ,

       { "$addFields": {
"shapes": {
  "$filter": {
    "input": {
      "$map": {
        "input": "$shapes",
        "as": "sa",
        "in": {
         // "name": "$$sa.name",
          "fileArray": {
            "$filter": {
              "input": "$$sa.fileArray",
              "as": "sn",
              "cond": {
                "$and": [
                  { "$eq": [ "$$sn.fileid", "ID001" ] }//,
                 // { "$eq": [ "$$sn.otherField", 1 ] }
                ]
              }
            }
          }             
        }
      },
    },
    "as": "sa",
    "cond": {
      "$and": [
        { "$eq": [ "$$sa.color", "blue" ] }
        //,{ "$gt": [ { "$size": "$$sa.someNestedArray" }, 0 ] }
      ]
    }
  }
      }
      }}
   ])

此查询返回零结果:

       {
        "_id" : ObjectId("562e7c594c12942f08fe4192"),
          "shapes" : [] 
           }

请知道我哪里出错了 此致

克里斯

0 个答案:

没有答案