Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing PHP and MongoDB sorting results based on key AND value?
    text
    copied!<p>For my case i am using MongoDB to store a whole bunch of products from 50 countries, entry in DB looks something like this:</p> <pre><code>{ _id: xxxxxxxxxxxxxxx, country: 'au', title: 'Equipment X', price: 1000, }, { _id: xxxxxxxxxxxxxxy, country: 'us', title: 'Equipment Y', price: 1000, }, ... ... </code></pre> <p>I would like to know if it is at all possible to query all products and sort by country from <b>au</b> FIRST, then the rest of the products after that. The simple MongoDB sort seems to only sort by key. If it is possible, does it involve map/reduce?</p> <p><strong>Edit: A more detailed example</strong></p> <p>Documents in collection:</p> <pre><code>{ country:'cn', title:'Equipment A', price:'100'}, { country:'au', title:'Equipment B', price:'100'}, { country:'za', title:'Equipment C', price:'100'}, { country:'us', title:'Equipment D', price:'100'}, { country:'nz', title:'Equipment E', price:'100'}, { country:'it', title:'Equipment F', price:'100'}, { country:'nz', title:'Equipment G', price:'100'}, { country:'au', title:'Equipment H', price:'100'}, </code></pre> <p>I am looking for a sort that will return products from <strong>nz</strong> to be at the top and then follow by all other products, like this:</p> <pre><code>{ country:'nz', title:'Equipment E', price:'100'}, { country:'nz', title:'Equipment G', price:'100'}, { country:'au', title:'Equipment B', price:'100'}, { country:'au', title:'Equipment H', price:'100'}, { country:'cn', title:'Equipment A', price:'100'}, { country:'it', title:'Equipment F', price:'100'}, { country:'us', title:'Equipment D', price:'100'}, { country:'za', title:'Equipment C', price:'100'}, </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload