1

I have a collection in which I store data in below format I want to apply sort by in below collection.

{
"job_count" : [ 
        ObjectId("58eb607531f78831a8894a3e"),
        ObjectId("58eb607531f78831a8894a3e"),
        ObjectId("58eb607531f78831a8894a3e")
    ]
},
{
"job_count" : [ 
        ObjectId("58eb607531f78831a8894a3e")
    ]
},
{
"job_count" : [ 
        ObjectId("58eb607531f78831a8894a3e"),
        ObjectId("58eb607531f78831a8894a3e")
    ]
}

i want data to be like as below

{
    "job_count" : [ 
            ObjectId("58eb607531f78831a8894a3e"),
            ObjectId("58eb607531f78831a8894a3e"),
            ObjectId("58eb607531f78831a8894a3e")
        ]
    },
    {
    "job_count" : [ 
            ObjectId("58eb607531f78831a8894a3e"),
            ObjectId("58eb607531f78831a8894a3e")
        ]
    },
    {
    "job_count" : [ 
            ObjectId("58eb607531f78831a8894a3e")
        ]
    }

my complete query is

Jobs.aggregate(
            {"$match"  : $condArray},
            {"$unwind" : { path: "$mytradesmen.hired", preserveNullAndEmptyArrays: true}},
            {"$lookup" : {
                        "from":"users",
                        "localField":"mytradesmen.hired",
                        "foreignField":"_id",
                        "as": "user_details"
                    }
            },
            {"$unwind": { path: "$user_details", preserveNullAndEmptyArrays: true}},

            { "$sort" : {"job_count":-1}})

Can anyone help me figure out the query i should modify to get the expected result, please let me know in case of any further detail required i will edit my question accordingly

1 Answer 1

2

Use the $size operator to create an extra field that holds the count of the elements in the array and then $sort on that field:

Jobs.aggregate([
    {
        "$project": {
            "count": { "$size": "$job_count" },
            "job_count": 1
        }
    },
    { "$sort" : { "count": -1 } }
])
Sign up to request clarification or add additional context in comments.

2 Comments

what if i want this to be conditional actually by using project i will have to mention all the field i need to display which will be quiet time taking is there any way to make this condition optional
There is a better way if you have MongoDB version 3.4 and greater which has the $addFields operator, equivalent to a $project stage that explicitly specifies all existing fields in the input documents and adds the new fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.