Lo memorizzerei nell'ordine in cui lo desideri. Oppure ordinalo dopo averlo estratto, dal lato del cliente.
Se nessuno di questi sono possibili, è possibile utilizzare il aggregation framework:
> db.test.insert({answers: [
... {name: 'paul', state: 'RU'},
... {name: 'steve', state: 'US'},
... {name: 'mike', state: 'DE'}]});
> db.test.insert({answers: [
... {name: 'paul', state: 'RU'},
... {name: 'steve', state: 'US'},
... {name: 'xavier', state: 'TX'}]});
db.test.aggregate([
{$unwind: "$answers"},
{$sort: {"answers.name":1}},
{$group: {_id:"$_id", answers: {$push:"$answers"}}}
]);
produce:
{
"result" : [
{
"_id" : ObjectId("5053b2477d820880c3469364"),
"answers" : [
{
"name" : "paul",
"state" : "RU"
},
{
"name" : "steve",
"state" : "US"
},
{
"name" : "xavier",
"state" : "TX"
}
]
},
{
"_id" : ObjectId("5053af9f7d820880c3469363"),
"answers" : [
{
"name" : "mike",
"state" : "DE"
},
{
"name" : "paul",
"state" : "RU"
},
{
"name" : "steve",
"state" : "US"
}
]
}
],
"ok" : 1
}
fonte
2012-09-14 22:42:19
Hai bisogno di virgolette intorno ai tuoi tasti "" answer.name "'. Ma non credo che il tuo codice faccia quello che sta cercando ... –
Il tuo esempio elencherà tutti i documenti con i loro campi '_id' e' name', ordinati per nome in ogni array. 'Sort()' funziona a livello di documento e non riordina le matrici all'interno dei documenti. – Stennie