Hello,
I am new to mongoDB. From documentation, it says the query result can be sorted in multiple fields. I tried to sort by the first field (‘65534’) in date format, then the second field (‘65533’) in number format. Here is the query I issued and the result produced:
db.getCollection('test_msg').find({},{'65534':1,'65533':1}).sort({'65534':1,'65533':1})
/* 1 */
{
"_id" : ObjectId("5e9fa79a7b6a0000a5005962"),
"65534" : ISODate("2020-04-22T02:10:34.628Z"),
"65533" : NumberLong(0)
}
/* 2 */
{
"_id" : ObjectId("5e9fa79a7b6a0000a5005964"),
"65534" : ISODate("2020-04-22T02:10:34.907Z"),
"65533" : NumberLong(0)
}
/* 3 */
{
"_id" : ObjectId("5e9fa79b7b6a0000a5005967"),
"65534" : ISODate("2020-04-22T02:10:35.177Z"),
"65533" : NumberLong(0)
}
/* 4 */
{
"_id" : ObjectId("5e9fa79b7b6a0000a500596c"),
"65534" : ISODate("2020-04-22T02:10:35.452Z"),
"65533" : NumberLong(0)
}
/* 5 */
{
"_id" : ObjectId("5e9fa79b7b6a0000a500596e"),
"65534" : ISODate("2020-04-22T02:10:35.456Z"),
"65533" : NumberLong(0)
}
/* 6 */
{
"_id" : ObjectId("5e9fa79b7b6a0000a5005971"),
"65534" : ISODate("2020-04-22T02:10:35.459Z"),
"65533" : NumberLong(0)
}
/* 7 */
{
"_id" : ObjectId("5e9fa79b7b6a0000a5005975"),
"65534" : ISODate("2020-04-22T02:10:35.733Z"),
"65533" : NumberLong(0)
}
/* 8 */
{
"_id" : ObjectId("5e9fa79c7b6a0000a5005979"),
"65534" : ISODate("2020-04-22T02:10:36.576Z"),
"65533" : NumberLong(0)
}
/* 9 */
{
"_id" : ObjectId("5e9fa79c7b6a0000a5005980"),
"65534" : ISODate("2020-04-22T02:10:36.857Z"),
"65533" : NumberLong(0)
}
/* 10 */
**{**
** "_id" : ObjectId("5e9fa79b7b6a0000a5005969"),**
** "65534" : ISODate("2020-04-22T02:10:35.181Z"),**
** "65533" : NumberLong(1)**
**}**
/* 11 */
{
"_id" : ObjectId("5e9fa79c7b6a0000a500597d"),
"65534" : ISODate("2020-04-22T02:10:36.580Z"),
"65533" : NumberLong(1)
}
/* 12 */
{
"_id" : ObjectId("5e9fa79c7b6a0000a5005984"),
"65534" : ISODate("2020-04-22T02:10:36.861Z"),
"65533" : NumberLong(1)
}
/* 13 */
{
"_id" : ObjectId("5e9fa79c7b6a0000a5005986"),
"65534" : ISODate("2020-04-22T02:10:36.862Z"),
"65533" : NumberLong(2)
}
You can spot well that the returned item #10 is not in the order as the sorting criteria: its date field value is earlier than the former item #9. Well, I found the output is like sorting only using the numeric field ‘65533’.
I tried creating an index {‘65534’:1,‘65533’:1} but it did not help. [Well, I don’t think it helps other than performance matter; am I right?]
I tested on Community edition 4.2.6, 4.2.5, 4.0.18 but all come to the results not in my expectation.
Could any expert tell whether I have a wrong understanding of the documentation or mongodb behavior? What is the correct way to produce a my expected sorting result of multiple fields in my case?
Thank you first for your advice.
Amon