简体   繁体   English

猫鼬如何使用$ elemMatch嵌套数组

[英]Mongoose how to use $elemMatch for nested array

I have to used below Collection, 我必须在收藏下面使用

  {
  "_id": ObjectId("..."),
  "modules": [
    {
      "name": "AAA",
      "group": [
        {
          "name": "g1",
          "ID":1
        },
        {
          "name": "g2",
          "ID":2
        }
      ]
    },
    {
      "name": "BBB",
      "group": [
        {
          "name": "g3",
          "ID":3
        },
        {
          "name": "g4",
          "ID":4
        }
      ]
    }
  ]
}

I have to use below code, 我必须使用以下代码,

test.find({'modules.group':{"$elemMatch":{'ID':1}}},{'modules.$.group': 1}).lean().exec(function(err, results) {

});

but the above code returns 但是上面的代码返回

"_id": ObjectId("..."),
"modules": [
    {
      "name": "AAA",
      "group": [
        {
          "name": "g1",
          "ID":1
        },
        {
          "name": "g2",
          "ID":2
        }
      ]
    }]

but i need only match Values array ID, I need below response, 但我只需要匹配Values数组ID,需要以下响应,

"_id": ObjectId("..."),
"modules": [
    {
      "name": "AAA",
      "group": [
        {
          "name": "g1",
          "ID":1
        }
    }]

Please give some solution to solve this elementmatch problem... 请提供一些解决方案以解决此elementmatch问题...

You could do it through aggregate , here are the sample codes. 您可以通过aggregate ,这是示例代码。

test.aggregate()
     .unwind('modules')
     .project({
         "_id": 1,
         "modules": {
             "$filter": {
                  "input": "$modules.group",
                  "as": "elem",
                  "cond": { "$eq": [ "$$elem.ID", 1 ] }
             }
         }
     })
     .exec(function(err, ret){
     });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM