Home > OS >  Filter by object array element and return only the value of a field in the array object MongoDB
Filter by object array element and return only the value of a field in the array object MongoDB

Time:08-09

I'm using MongoDB 5.0.10 and the aggregation pipeline. I am trying to find out if there is a way to filter an array of objects AND return only the value of a field within the returned array object. I can easily filter the array based on a field value within the array. I currently can achieve what I want in 2 stages. I'm just trying to see if I can return a value within the same stage. I'm using a projection and $arrayElemAt to filter the array. Then I perform another projection to get the value I want.

Sample document:

{
  "_id": 1,
  "lastOpenedList": [
    {
      "_id": 4,
      "dateTime": {
        "$date": {
          "$numberLong": "1659970718606"
        }
      }
    }
  ]
}

First stage:

$project: {
'lastOpened':{$arrayElemAt: [
    {$filter: {
      input: "$lastOpenedList",
      cond: {
        $eq:[
          "$$this._id", '4'
          ]
      }
    }},0
    ]}
}

Second stage:

$project: {
'lastOpened': '$lastOpened.dateTime'
}

Result:

{
  "_id": 1,
  "lastOpened": 
    {
        "$date": {
          "$numberLong": "1659970718606"
        }
     }
}

CodePudding user response:

Query

  • filter can't change the member only keep it or not
  • we have 2 options $map $filter => map keep those we want, and null in others, and then with $filter remove those nulls
  • other option is $reduce, and keep only those we want, in general $reduce is the most powerful
  • here $reduce, and if match keep it

Playmongo

aggregate(
[{"$project": 
   {"_id": 0,
    "lastOpened": 
     {"$reduce": 
       {"input": "$lastOpenedList",
        "initialValue": null,
        "in": 
         {"$cond": 
           [{"$eq": ["$$this.dateTime", 2]}, "$$this.dateTime",
            "$$value"]}}}}}])
  • Related