Convert raw mongo query using $addFields and $switch to Symfony 4 doctrine query builder

I am trying to sort documents by introducing a new field with value based on certain criteria. This is the raw query:

db.getCollection('sample_collection').aggregate([
{
     $match :  { 
                 "status" : { "$in" :  ["draft" , "pending" , "active" , "rejected" ] }
             }
},
{
    $sort : { "_id" : -1 }
},
{ 
    $skip : 25
    
},
{
   $limit : 10
},
{ 
    $project : { "status" : 1 , "updated_at" : 1 , "activated_at" : 1 ,  "rejected_at" : 1  }
},
{            
    $addFields: {
            "sort_timestamp": {
                    $switch: {
                        branches: [
                                { case : { "$eq" : [ "$status" , "draft"  ]  },  then: "$updated_at" },
                                { case : { "$eq" : [ "$status" , "active"  ]  },  then: "$activated_at" },
                                { case : { "$eq" : [ "$status" , "rejected"  ]  },  then: "$rejected_at" },
                            ],
                         default: "updated_at"       
                        }
                }
        }
},
{
    $sort : { "sort_timestamp" : -1}
} ])

With Sample Documents :

{
  "_id" : ObjectId("5f22b931c121c32d522ecd93"),
  "status" : "draft",
  "created" : ISODate("2020-07-30T13:07:11.415Z"),
  "id" : 10
}

{
 "_id" : ObjectId("5f22b931c121c32d522ecd93"),
 "status" : "active",
 "activated_at" : ISODate("2020-07-30T13:07:11.415Z"),
 "id" : 11
}

Can someone plz help me in translating this raw query to the Symfony Query Builder.
I have tried with DoctrineODMMongoDBcreateAggregationBuilder.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *