skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. What about this?

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

    Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search