Answer the question
In order to leave comments, you need to log in
How to sort objects in mongo?
There is some kind of random collection, for example:
[
{_id: ..., ratingPosition: 1},
{_id: ..., ratingPosition: 2},
{_id: ... }, <== Без параметра ratingPosition
]
db.getCollection("goodsTreeNodes").aggregate(
[
{
"$facet" : {
"outputField1" : [
{
"$match" : {
"ratingPosition" : {
"$exists" : true
}
}
},
{
"$sort" : {
"ratingPosition" : 1.0
}
}
],
"outputField2" : [
{
"$match" : {
"ratingPosition" : {
"$exists" : false
}
}
},
{
"$sort" : {
"name" : 1.0
}
}
]
}
},
{
"$project" : {
"result" : {
"$concatArrays" : [
"$outputField1",
"$outputField2"
]
}
}
},
{
"$unwind" : {
"path" : "$result",
"includeArrayIndex" : "arrayIndex",
"preserveNullAndEmptyArrays" : false
}
},
{
"$replaceRoot" : {
"newRoot" : "$result"
}
}
],
{
"allowDiskUse" : false
}
);
Answer the question
In order to leave comments, you need to log in
You need to check for values.
https://docs.mongodb.com/manual/reference/operator...
Run 2 queries and combine the results, but not a great idea.
As an alternative - use aggregation and fill empty fields with zero and then sort.
In general, something is wrong with the application logic. The very presence of a sorting problem hints at a problem elsewhere.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question