Search code examples
mongodbmongodb-queryazure-cosmosdb-mongoapi

Querying a multi value array to retrieve specific value in mongodb


I have an array element in my document db with multiple parameters.This is how a single document looks like. I can search based on name which is unique. Is there a way to list all technologies associated with the name.

"name" : "Sam",
"date" : ISODate("2020-02-05T06:34:28.453Z"),
"technology" : [ 
    {
        "technologyId" : "1",
        "technologyName" : "tech1"
    }, 
    {
        "technologyId" : "2",
        "technologyName" : "tech2"
    }, 
    {
        "technologyId" : "3",
        "technologyName" : "tech3"
    }, 
    {
        "technologyId" : "4",
        "technologyName" : "tech4"
    }
],
"sector" : [ 
    {
        "sectorId" : "1",
        "sectorName" : "sector1"
    }, 
    {
        "sectorId" : "2",
        "sectorName" : "sector2"
    }, 
    {
        "sectorId" : "3",
        "sectorName" : "sector3"
    }, 
    {
        "sectorId" : "4",
        "sectorName" : "sector4"
    }
]

This is my simple query

db.getCollection('myCollection').find({'name':'Sam'})

Is there a way to retrieve all technologies for a name in a single query.

My output should have only tech1,tech2,tech3,tech4.


Solution

  • A two stage aggregation using $match, $project and $map.

    Query:

    db.collection.aggregate([
      {
        $match: {
          name: "Sam"
        }
      },
      {
        $project: {
          "name": "$name",
          "technologies": {
            $map: {
              input: "$technology",
              as: "t",
              in: "$$t.technologyName"
            }
          }
        }
      }
    ]);
    

    Result:

    [
      {
        "_id": ObjectId("5a934e000102030405000000"),
        "name": "Sam",
        "technologies": [
          "tech1",
          "tech2",
          "tech3",
          "tech4"
        ]
      }
    ]
    

    In case you don't want the name in the final O/P remove it from project stage.