简体   繁体   中英

MongoDB Sort collection by nested objects fields

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" } }
 ....

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM