복붙노트

[MONGODB] 두 번 중첩 된 배열에서 찾기 MongoDB를

MONGODB

두 번 중첩 된 배열에서 찾기 MongoDB를

나는 MongoDB의이 컬렉션을

{
"_id" : "777",
"someKey" : "someValue",
"someArray" : [
    {
        "name" : "name1",
        "someNestedArray" : [
            {
                "name" : "value"
            },
            {
                "name" : "delete me"
            }
        ]
    }
  ]
}

나는 someArray.someNestedArray.name에 따라 문서를 찾으려면 하지만 난 어떤 유용한 링크를 갱신 중첩 된 배열에 대한 모든 검색 결과를 찾을 수 없습니다 나는이 있지만 반환 아무것도 시도하지 있어요

db.mycollection.find({"someArray.$.someNestedArray":{"$elemMatch":{"name":"1"}}})
db.mycollection.find({"someArray.$.someNestedArray.$.name":"1"})

그리고 다른 어떤 것

내가 어떻게 두 번 중첩 된 배열하여 MongoDB의 요소에 의해 찾을 수 있습니까?

해결법

  1. ==============================

    1.가장 간단한 의미에서 이것은 단지 MongoDB에 의해 사용되는 "점 표기법"의 기본 형태를 따른다. 그와 상관없이 배열 내측 부재로는, 값이 일치하면에 배열되는 부재의 작동 :

    가장 간단한 의미에서 이것은 단지 MongoDB에 의해 사용되는 "점 표기법"의 기본 형태를 따른다. 그와 상관없이 배열 내측 부재로는, 값이 일치하면에 배열되는 부재의 작동 :

    db.mycollection.find({
        "someArray.someNestedArray.name": "value"
    })
    

    즉, elemMatch $ 사용하는 것이 일치하는 여러 필드를 들어, "하나의 필드"값 괜찮 :

    db.mycollection.find({
        "someArray": { 
            "$elemMatch": {
                "name": "name1",
                "someNestedArray": {
                    "$elemMatch": {
                        "name": "value",
                        "otherField": 1
                    }
                }
            }
        }
    })
    

    즉, 값과 일치하는 "경로"에서 필드에 무언가를 포함 할 문서와 일치합니다. 그렇게 만 일치하는 요소가 반환 된 결과 "일치 및 필터"를 구성하는 경우 인용,이, 위치 운영자 돌기가 불가능합니다 :

    우리는 $ 필터와 여기 $ 맵을 적용하여이 작업을 수행 할 수 있습니다. 은 "내부"배열이 "필터링"의 결과로 변경하고 "내부"이 모든 요소의 제거되었을 때 물론 "외부"배열 조건과 일치하지 않기 때문에 $ 맵이 정말 필요합니다.

    또 실제로 각 어레이 내에 맞도록 여러 특성을 갖는 예를 다음

    db.mycollection.aggregate([
      { "$match": {
        "someArray": {
          "$elemMatch": {
             "name": "name1",
             "someNestedArray": {
               "$elemMatch": {
                 "name": "value",
                 "otherField": 1
               }
             }
           }
        }
      }},
      { "$addFields": {
        "someArray": {
          "$filter": {
            "input": {
              "$map": {
                "input": "$someArray",
                "as": "sa",
                "in": {
                  "name": "$$sa.name",
                  "someNestedArray": {
                    "$filter": {
                      "input": "$$sa.someNestedArray",
                      "as": "sn",
                      "cond": {
                        "$and": [
                          { "$eq": [ "$$sn.name", "value" ] },
                          { "$eq": [ "$$sn.otherField", 1 ] }
                        ]
                      }
                    }
                  }             
                }
              },
            },
            "as": "sa",
            "cond": {
              "$and": [
                { "$eq": [ "$$sa.name", "name1" ] },
                { "$gt": [ { "$size": "$$sa.someNestedArray" }, 0 ] }
              ]
            }
          }
        }
      }}
    ])
    

    전체 내부 배열이 주목할 사실 경기에서 수행 할 때 그 결과를 거부 할 수 있도록이 자신을 "필터링"후에 따라서 "외부"배열의 $ 필터는 실제로 "내부"배열의 $ 크기로 보인다.

    "프로젝트"에만 일치하는 요소하기 위해, 당신은 .aggregate () 메소드가 필요합니다 :

    db.mycollection.aggregate([
        // Match possible documents
        { "$match": {
            "someArray.someNestedArray.name": "value"
        }},
    
        // Unwind each array
        { "$unwind": "$someArray" },
        { "$unwind": "$someArray.someNestedArray" },
    
        // Filter just the matching elements
        { "$match": {
            "someArray.someNestedArray.name": "value"
        }},
    
        // Group to inner array
        { "$group": {
            "_id": { 
                "_id": "$_id", 
                "name": "$someArray.name"
            },
            "someKey": { "$first": "$someKey" },
            "someNestedArray": { "$push": "$someArray.someNestedArray" }
        }},
    
        // Group to outer array
        { "$group": {
            "_id": "$_id._id",
            "someKey": { "$first": "$someKey" },
            "someArray": { "$push": {
                "name": "$_id.name",
                "someNestedArray": "$someNestedArray"
            }}
        }} 
    ])
    

    즉, 문서 내에서 하나 개 이상의 결과를 중첩 배열에서 "필터"를 일치로 할 수 있습니다.

  2. ==============================

    2.당신은 또한 다음과 같은 것을 시도 할 수 있습니다 :

    당신은 또한 다음과 같은 것을 시도 할 수 있습니다 :

    db.collection.aggregate(
        { $unwind: '$someArray' },
        {
            $project: {
                'filteredValue': {
                    $filter: {
                      input: "$someArray.someNestedArray",
                      as: "someObj",
                      cond: { $eq: [ '$$someObj.name', 'delete me' ] }
                    }
                }
            }
        }
    )
    
  3. from https://stackoverflow.com/questions/29071748/find-in-double-nested-array-mongodb by cc-by-sa and MIT license