1

I have collection with the following structure:

{

...

TitleComposite: [
    {
        TitleType: "01",
        TitleText "Title Important"
    },
    {
        TitleType: "03",
        TitleText: "Not so important"
    }
]

...

}

What I want to do is to sort collection by TitleComposite.TitleText which has TitleType equal to "01".

So, only string "Title Important" will take part in sorting. I'm not sure is it possible and if yes, is it effective? I have quite large collection of documents (about 11 000 for now) and maybe creating of separate field for sorting purpose only is better?


UPD

@TrudBert, I tried what you advice and made the following request:

db.onix_feed.aggregate(
    {$unwind: '$titleComposite'},
    {$match:{'titleComposite.titleType':"01"}},
    {$sort:{'titleCompostite.titleText':1}},
    {$project: {"titleComposite.titleText":1, "_id": 0}}
)

But return result doesn't seem to be sorted by titleText:

{ "titleComposite" : { "titleText" : "Small Scale Mining" } }
{ "titleComposite" : { "titleText" : "Cane Sugar" } }
{ "titleComposite" : { "titleText" : "Microenterprises In Developing Countries" } }
{ "titleComposite" : { "titleText" : "The Development of Indian Silk" } }
{ "titleComposite" : { "titleText" : "Stoves for People" } }
 ....
1
  • I had a typo in my answer it sorts for titleCompostite.titleText edited that Commented Aug 23, 2014 at 6:15

1 Answer 1

1

You could do it with aggregate but you will loose the other TitleTexts on the way (in the result documents not the collection):

db.test.aggregate({$unwind: '$TitleComposite'},
                  {$match:{'TitleComposite.TitleType':"01"}},
                  {$sort:{'TitleComposite.TitleText':1}})

It will return de documents orderd by the TitleText with TitleType=01 but it will loose the other TitleComosite Elements on the way (short explanation: $unwind creates a single (result) document for each element in TitleComposite, $match filters out the ones where TitleType is 01 and $sort sorts them by TitleText)

Creating a seperate field (idealy as an index) for sorting would probably be faster but would also make you change all documents.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for answer. I tried your advice, and added comment to the post. Maybe I did something wrong?
I tested your solution and it really sorted documents by nested object field. Am I right that documents which don't have "titleComposite" at all will be excluded from results?
Yes, they should be excluded.

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.