簡體   English   中英

貓鼬如何使用$ elemMatch嵌套數組

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

我必須在收藏下面使用

  {
  "_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
        }
      ]
    }
  ]
}

我必須使用以下代碼,

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

});

但是上面的代碼返回

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

但我只需要匹配Values數組ID,需要以下響應,

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

請提供一些解決方案以解決此elementmatch問題...

您可以通過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