Monday 29 May 2017

Sorting MongoDB result on the basis of the value of a specific Item in a nested SubDocument Array

My MongoDB DB Structure of the Item collection is as follows:

{
    _id: <ObjectId>,
    attributes: "MyName",
    attributes: [
                    {
                        "attrName" : "name1",
                        "attrVal" : "val1",
                    },
                    {
                        "attrName" : "name2",
                        "attrVal" : "val2",
                    },
                    {
                        "attrName" : "name3",
                        "attrVal" : "val3",
                    },
                    {
                        "attrName" : "name4",
                        "attrVal" : "val4",
                    },
                    {
                        "attrName" : "nameN",
                        "attrVal" : "valN",
                    }
                ] 
}

Now, I want to sort(multi sort) this on the basis of the attrVal of the element of atttributes subdocument where attrName is ,say, nameX. The passed name is entered by user on runtime.

Also, it is not necessary thst all items in the collection have all the attibutes, but i want to sort even if only 1 item has that p[articual attribute.

How can I go about doing this?



via Ayush Gupta

No comments:

Post a Comment