I have a simple Collection for understand sort in MongoDB
my documents are:
{
"_id" : ObjectId("54b94985d74d670613e4fd35"),
"tag" : [
"A",
"B",
"Z"
]
}
{
"_id" : ObjectId("54b949c9d74d670613e4fd36"),
"tag" : [
"D",
"E",
"F"
]
}
{
"_id" : ObjectId("54b949dfd74d670613e4fd37"),
"tag" : [
"G",
"H",
"I"
]
}
When I sort by Tag I Have these results
db.candy.find().sort({tag:1})
{
"_id" : ObjectId("54b94985d74d670613e4fd35"),
"tag" : [
"A",
"B",
"Z"
]
}
{
"_id" : ObjectId("54b949c9d74d670613e4fd36"),
"tag" : [
"D",
"E",
"F"
]
}
{
"_id" : ObjectId("54b949dfd74d670613e4fd37"),
"tag" : [
"G",
"H",
"I"
]
}
Instead with tag:-1
db.candy.find().sort({tag:-1})
{
"_id" : ObjectId("54b94985d74d670613e4fd35"),
"tag" : [
"A",
"B",
"Z"
]
}
{
"_id" : ObjectId("54b949dfd74d670613e4fd37"),
"tag" : [
"G",
"H",
"I"
]
}
{
"_id" : ObjectId("54b949c9d74d670613e4fd36"),
"tag" : [
"D",
"E",
"F"
]
}
The results are very similar, the first object It's the same and Change only the second and the third. Same Results with Array of object. My question is: How it works the sort? I know that the letter A is the first letter of Alphabetic ( ASCII CODE ) and the Z is the last. The mongo check each element ( or object ) of array ? And Why the order inside array is the same when I use tag:-1 and tag:1 ? I expect something like
tag:1
{
"_id" : ObjectId("54b94985d74d670613e4fd35"),
"tag" : [
"A",
"B",
"Z"
]
}
And tag:-1
{
"_id" : ObjectId("54b94985d74d670613e4fd35"),
"tag" : [
"Z",
"A",
"B"
]
}