Erez Shlomo
Erez Shlomo

Reputation: 2282

MongoDB - Merge Array of Strings With 2-Dimensional Array

I have a MongoDB document which looks like this:

  "skills" : [ 
    [ 
        ObjectId("5dbaf9dd95e131fb3e23ef47"), 
        ObjectId("5dc3cd49796b017513c1bc6d"), 
        ObjectId("5dc3cd52796b017513c1bc75"), 
        ObjectId("5dc3cd5b796b017513c1bc82")
    ], 
    [ 
        ObjectId("5dbaf9dd95e131fb3e23ef47"), 
        ObjectId("5dbaf7fc251cee32ce4d3f84")
    ]
 ],
  "names" : [ 
    "John Davis", 
    "Dan Malko"
    ]

(Array of names - string, and Array of arrays of skills)

And I want the result to be:

"skillsWithNames": [
    {
        "name": "John Davis",
        "skills": [ 
        ObjectId("5dbaf9dd95e131fb3e23ef47"), 
        ObjectId("5dc3cd49796b017513c1bc6d"), 
        ObjectId("5dc3cd52796b017513c1bc75"), 
        ObjectId("5dc3cd5b796b017513c1bc82")
        ]
    },
    {
        "name":"Dan Malko",
        "skills":[ 
            ObjectId("5dbaf9dd95e131fb3e23ef47"), 
            ObjectId("5dbaf7fc251cee32ce4d3f84")
            ]
    }
]

(Array which contains objects, where each object contains a name and the skills).

The indexes are the same for both arrays, so skills[0] belong to the person's name[0].

What is the correct query to do this?

Thanks.

Upvotes: 2

Views: 106

Answers (1)

Ashh
Ashh

Reputation: 46491

You can use below aggregation

db.collection.aggregate([
  { "$project": {
    "skillsWithName": {
      "$map": {
        "input": "$skills",
        "in": {
          "name": {
            "$arrayElemAt": [
              "$names",
              { "$indexOfArray": ["$skills", "$$this"] }
            ]
          },
          "skills": "$$this"
        }
      }
    }
  }}
])

Output

[
  {
    "skillsWithName": [
      {
        "name": "John Davis",
        "skills": [
          ObjectId("5dbaf9dd95e131fb3e23ef47"),
          ObjectId("5dc3cd49796b017513c1bc6d"),
          ObjectId("5dc3cd52796b017513c1bc75"),
          ObjectId("5dc3cd5b796b017513c1bc82")
        ]
      },
      {
        "name": "Dan Malko",
        "skills": [
          ObjectId("5dbaf9dd95e131fb3e23ef47"),
          ObjectId("5dbaf7fc251cee32ce4d3f84")
        ]
      }
    ]
  }
]

Upvotes: 1

Related Questions