what is the equivalent mongodb query for the following mysql query or how to write query to get the results
SELECT name, species FROM pet
ORDER BY FIELD(species, 'dog','cat','snake','bird'), name ASC
what is the equivalent mongodb query for the following mysql query or how to write query to get the results
SELECT name, species FROM pet
ORDER BY FIELD(species, 'dog','cat','snake','bird'), name ASC
What you need to do to achieve this is weight your responses using aggregate
db.collection.aggregate({
{ "$project": {
"name": 1,
"species", 1
"weight": { "$cond": [
{ "$eq": [ "$species", "dog" ] },
4,
{ "$cond": [
{ "$eq": [ "$species", "cat" ] },
3,
{ "$cond": [
{ "$eq": [ "$species", "snake" ] },
2,
{ "$cond": [
{ "$eq": [ "$species", "bird" ] },
1,
0
]}
]}
]}
]}
},
{ "$sort": { "weight": -1 }}
])
So you use the $cond operator which is a ternary operation to evaluate what the current value of the field is. If it matches the condition, assign the value to weight, if not move on to the next one, until if it did not match then assign 0.
Sort descending on the weight, and the results come out in the order you want.
You can see how to generate this nested structure in code here.