Home > Net >  Project one field from specific object element in an array mongodb
Project one field from specific object element in an array mongodb

Time:03-25

I have a collection:

{
    "_id": 1,
    "_deleted": false,
    "customFields": [{
        "fieldName": "sapID",
        "value": ""
    }, {
        "fieldName": "salesTerritory",
        "value": ""
    }, {
        "fieldName": "clientType",
        "value": "Corporate"
    }],
}

How can I project(aggregate) only the value field of the element with fieldName = "clientType":

db.collection.aggregate(
    {
        $project:{value:<code>}
    }
)

I tried $filter but it does not work

CodePudding user response:

db.collection.aggregate([
  {
    $project: {
      "customFields.value": 1
    }
  }
])

mongoplayground


db.collection.aggregate([
  {
    $set: {
      customFields: {
        $map: {
          input: "$customFields",
          as: "c",
          in: {
            $cond: {
              if: { "$eq": [ "$$c.fieldName", "clientType" ] },
              then: { value: "$$c.value" },
              else: "$$c"
            }
          }
        }
      }
    }
  }
])

mongoplayground

CodePudding user response:

What about this?

db.collection.aggregate([
   {
      $project: {
         customFields: {
            $filter: {
               input: "$customFields",
               $cond: { $eq: ["$$this.fieldName", "clientType"] }
            }
         }
      }
   }
])

Mongo Playground

  • Related